JPA:加入 JPQL [英] JPA: JOIN in JPQL
问题描述
我以为我知道如何在 JPQL
中使用 JOIN
但显然不知道.有人可以帮我吗?
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
这给了我例外
org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing the query
Internal Exception: org.eclipse.persistence.internal.libraries.antlr.runtime.EarlyExitException
Users
与 Groups
有一对多的关系.
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();
***
代表上面的查询名称.那么 fname
和 lname
是在 temp
内部连接在一起还是我得到一个 List
回来?
***
represent the query name above. So does fname
and lname
concatenated together inside temp
or I get a List<String>
back?
推荐答案
在JPQL中加入一对多关系如下:
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
在select
子句中指定多个属性时,返回结果为Object[]
:
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];
顺便说一下,为什么您的实体以复数形式命名,这令人困惑.如果你想有复数的表名,你可以使用 @Table
来明确指定实体的表名,这样它就不会干扰保留字:
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 { ... }
这篇关于JPA:加入 JPQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!