假设我要获取MyEntity
ID小于10的所有行。此实体包含一个Another
实体列表。我希望仅通过的子集来获取此列表listAnother
。此子集仅包含Another
其中user
包含的特定子集。
基本上在SQL中将是这样的:
SELECT * FROM myentity m
LEFT JOIN another a
ON m.idTable=a.my_entity
AND a.user = "test1"
WHERE m.idTable < 10;
但是,我没有设法将此查询转换为jpql。
我的实体是这样的:
@Entity
public class MyEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int idTable;
@OneToMany(mappedBy = "myEntity")
private List<Another> listAnother;
}
@Entity
public class Another implements Serializable {
@Id
private int idAnother;
// bi-directional many-to-one association to Thethread
@ManyToOne(fetch = FetchType.LAZY)
private MyEntity myEntity;
@ManyToOne(fetch = FetchType.LAZY)
private User user;
}
@Entity
public class User implements Serializable {
@Id
private String username;
}
在jpa中,我可以这样做:
SELECT m FROM MyEntity where m.idTable < 10;
然后,对于我从此列表中获得的每个实体,请调用此命令:
SELECT a FROM Another Where a.user.username=:'test' AND a.myEntity=:entity;
但是,我想一次完成所有查询。我可以使用标准吗?我没有花时间去学习它,但是如果有可能的话,我会的。
JPQL和Critaria API在您可以使用它们表达的方面是相等的。使用Criteria可以实现JPQL,反之亦然。
使用JPQL,您可以通过以下方式将两个查询简单地合并为一个:
SELECT a FROM Another a Where a.user.username=:test AND a.myEntity.idTable < 10
您可以使用点符号(。)来连接查询中的多个实体,前提是该关系是X对1的。如果您具有X对多关系,则需要使用JPQL JOIN,这不是很复杂。(LEFT)JOIN的示例:
SELECT m FROM MyEntity m LEFT JOIN m.listAnother a Where a.user.username=:test AND m.idTable < 10
结果当然是不相等的-在第一种情况下,您将获得另一个实体的列表,并且可以通过a.myEntity获得MyEntity,在第二种情况下,您将获得MyEntity的列表,这些列表都具有至少一个具有给定用户的另一个实体
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句