Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: JOIN in JPQL

I thought I know how to use JOIN in JPQL but apparently not. Can anyone help me?

select b.fname, b.lname from Users b JOIN Groups c where c.groupName = :groupName 

This give me Exception

org.eclipse.persistence.exceptions.JPQLException Exception Description: Syntax error parsing the query Internal Exception: org.eclipse.persistence.internal.libraries.antlr.runtime.EarlyExitException 

Users have a OneToMany relationship with Groups.

Users.java

@Entity public class Users implements Serializable{      @OneToMany(mappedBy="user", cascade=CascadeType.ALL)     List<Groups> groups = null; } 

Groups.java

@Entity public class Groups implements Serializable {     @ManyToOne     @JoinColumn(name="USERID")     private Users user; } 

My second question is let say this query return a unique result, then if I do

String temp = (String) em.createNamedQuery("***")     .setParameter("groupName", groupName)     .getSingleResult(); 

*** represent the query name above. So does fname and lname concatenated together inside temp or I get a List<String> back?

like image 378
Thang Pham Avatar asked Sep 16 '10 20:09

Thang Pham


People also ask

Can JPQL join operations?

We can also join multiple entities in a single JPQL query: @Test public void whenMultipleEntitiesAreListedWithJoin_ThenCreatesMultipleJoins() { TypedQuery<Phone> query = entityManager.

Can we use inner join in JPQL?

JPQL provides an additional type of identification variable, a join variable, which represent a more limited iteration over specified collections of objects. In JPQL, JOIN can only appear in a FROM clause. The INNER keyword is optional (i.e. INNER JOIN is equivalent to JOIN).

How do I join two entities in JPA?

The only way to join two unrelated entities with JPA 2.1 and Hibernate versions older than 5.1, is to create a cross join and reduce the cartesian product in the WHERE statement. This is harder to read and does not support outer joins. Hibernate 5.1 introduced explicit joins on unrelated entities.


1 Answers

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName  

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")     .setParameter("groupName", groupName)     .getSingleResult();  String fname = (String) temp[0]; String lname = (String) temp[1]; 

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")      public class User implements Serializable { ... }  
like image 107
axtavt Avatar answered Sep 20 '22 16:09

axtavt