views:

188

answers:

1
+1  Q: 

JPA: JOIN in JPQL

I thought I know how to 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?

+2  A: 

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 { ... } 
axtavt
yup, I actually just figure that out. Thanks a lot. Did u get a chance to see my second question. Now I return `fname` and `lname`, what data type does the result come back? I try `String`, and it clearly not right, since it says it `Object cannot be cast to String`. The plural form, trust me I hate it too, but since `User`, `Group` and many other keywords are reserved for SQL.
Harry Pham
@Harry: Updated.
axtavt
super Thanks !!!!
Harry Pham