I have two tables: Customers and Commands, it's a @OneToMany
relation from Client to Commands, one client have many Commands.
the table commands contain : idCommand, date, nameCommande, idCustomer
.
the table customers contain: idCustomer, nameClient, email
.
All the JPA and EJB are set up and I can easily get a list of Commands or Clients using an HQL query in a managed bean and list them in a JSP using this code.
public List<Commande> selectAllCommandes() {
List<Commande> commandes = em.createQuery("select c from Commande c").getResultList();
return commandes;
}
public List<Customer> selectAllCustomers() {
List<Customer> customers = em.createQuery("select cu from Customer cu").getResultList();
return customers;
}
How do I join the two tables with the idCustomer
column in a way to show the name of client instead his id? I've used this HQL query
SELECT c.date, c.name Commande, cu.nameClient FROM Commande AS c, Customer AS cu WHERE cu.idCustomer = c.idCustomer
But I have no idea about the List<>
type that I need to use to get the result/
If you map the reverse relation in the Commande
entity ...
public class Commande {
...
@ManyToOne(mappedBy="commande")
private Client client;
// getter and setter ...
}
(Here, mappedBy
is getting the name of the @OneToMany
property set up at the
other side of the relationship)
Then after executing your query SELECT c FROM Commande c
you would get a list of Commande
objects, and for each one of them you could get the name of the client using: thisCommande.getClient().getName()
.