java 一对多关系的 JPQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42303746/
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-11-03 06:31:44  来源:igfitidea点击:

JPQL for One to Many Relationship

javamysqljpaeclipselinkjpql

提问by Ihsan Haikal

I'm trying to create a JPQL for one to many relationship, namely user and device as 1 user can have one to many devices. I want to find the whole object of the device if it is owned by the user and the device name is correct.

我正在尝试为一对多关系创建 JPQL,即用户和设备,因为 1 个用户可以拥有一对多设备。如果设备归用户所有并且设备名称正确,我想找到设备的整个对象。

If it is a SQL query then I can just do the query only for the device as follow:

如果是 SQL 查询,那么我可以只对设备进行查询,如下所示:

select * from DEVICE where USER_ID = 2 and DEVICENAME = "mypc";

where USER_ID is the foreign key in DEVICE table. But how can I do the JPQL query for the user and device table? Here are some info for User and Device class

其中 USER_ID 是 DEVICE 表中的外键。但是如何对用户和设备表进行 JPQL 查询?以下是用户和设备类的一些信息

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
public int id;
public String username;
public String firstname;
public String lastname;
public String hashPassword;

@OneToMany(mappedBy = "user")
public List<Device> devices = new ArrayList<Device>();


}

@Entity
public class Device {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    public int id;
    public String deviceName;
    @ManyToOne
    public User user;
    String deviceOS;
    String deviceType;
    String attributes;
    boolean standard;
}

回答by ozgur

Example JPA Query:Documention

示例 JPA 查询:文档

Query query = entityManager.createQuery("SELECT di FROM Device di JOIN di.user u WHERE u.id=:userId and di.deviceName=:deviceName");
query.setParameter("userId",userId );
query.setParameter("deviceName",deviceName);
List<Device> result = query.getResultList();

回答by Philipp Merkle

You can use JPQL path expressionsin your query to navigate from one entity to another, or to refer to attributes of an entity.

您可以在查询中使用JPQL 路径表达式从一个实体导航到另一个实体,或引用实体的属性。

More specifically, path expressions are useful to navigate along @ManyToOneor @OneToOnerelationships, e.g.:

更具体地说,路径表达式对于导航@ManyToOne@OneToOne关系很有用,例如:

SELECT d FROM Device d WHERE d.user.id = :userId AND d.deviceName = :deviceName

Here, d.user.idis a path expression.

这里,d.user.id是一个路径表达式。

For a general overview of JPQL, have a look at the great Wikibooks article.

有关 JPQL 的一般概述,请查看很棒的Wikibooks 文章