JPA:加入JPQL [英] JPA: JOIN in JPQL

查看:100
本文介绍了JPA:加入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

用户与<$有一个OneToMany关系C $ C>组。

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 或I中连接在一起得到列表< String> 返回?

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

推荐答案

加入一个 - JPQL中的to-many关系如下所示:

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];

顺便说一下,为什么你的实体以复数形式命名,令人困惑。如果您希望将表名复数形式,可以使用 @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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆