Java JPA:加入 JPQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3730625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:00:55  来源:igfitidea点击:

JPA: JOIN in JPQL

javajpaeclipselinkjpql

提问by Thang Pham

I thought I know how to use JOINin JPQLbut apparently not. Can anyone help me?

我以为我知道如何使用JOINinJPQL但显然不知道。谁能帮我?

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

Usershave a OneToMany relationship with Groups.

Users有 OneToMany 关系Groups

Users.java

Users.java

@Entity
public class Users implements Serializable{

    @OneToMany(mappedBy="user", cascade=CascadeType.ALL)
    List<Groups> groups = null;
}

Groups.java

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 fnameand lnameconcatenated together inside tempor I get a List<String>back?

***代表上面的查询名称。那么是fnamelname内部连接在一起temp还是我得到了List<String>回报?

采纳答案by axtavt

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

在 JPQL 中加入一对多关系如下所示:

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

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

select子句中指定了多个属性时,结果返回为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 @Tableto specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

顺便说一下,为什么您的实体以复数形式命名,这令人困惑。如果你想有复数的表名,你可以使用@Table显式指定实体的表名,这样它就不会干扰保留字:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... }