JPA: JOIN in JPQL

后端 未结 1 1944
执笔经年
执笔经年 2020-12-01 06:08

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         


        
相关标签:
1条回答
  • 2020-12-01 06:33

    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 { ... } 
    
    0 讨论(0)
提交回复
热议问题