简体   繁体   English

JPQL无法正常工作

[英]JPQL does not work properly

Parent class: 家长班:

@Table(name = "users")
class User {
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
List<Gender> genders = new ArrayList<>();

Child class: 子班:

@Table(name = "gender")
class Gender {
@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "userId", nullable = false)
User user;
String sex;

my goal in MySQL: 我在MySQL中的目标:

SELECT * FROM users a LEFT JOIN genders b ON a.id=b.id WHERE b.sex='dasd' 从用户中选择*从左加入性别b在a.id = b.id上b.sex ='dasd'

Returns 1 ROW It works good. 返回1 ROW,效果很好。 I got only one record that meets this condition. 我只有一条符合这一条件的记录。

but same code in JPQL: 但是JPQL中的相同代码:

SELECT a FROM Users a LEFT JOIN a.genders b WHERE b.sex ='dasd' 从用户中选择一个左联接a。性别b在哪里b.sex ='dasd'

Returns: one user – correctly and ALL genders in table Gender, but I dont want to ALL I want only when sex ='dasd' and only one record that meets this condition.btw JPQL generate N+1 issue and for every subquery ignoring condtion sex ='dasd' 返回值:一个用户–正确,并且表Gender中的所有性别均正确,但是我只希望当sex ='dasd'并且只有一个满足此条件的记录时才想要。btw JPQL生成N + 1问题,并且每个子查询都忽略条件性别='dasd'

How to write subquery satisfying the condition? 如何编写满足条件的子查询? Can I force subquery to return only Gender matching the JPQL query? 我可以强制子查询仅返回与JPQL查询匹配的性别吗?

In JPQL you select from entity not table, 在JPQL中,您从实体而非表格中选择,

SELECT a FROM User a LEFT JOIN a.genders b WHERE b.sex ='dasd'

Since you configured the a.genders list as EAGER, every time you select an User, it will fetch all genders the user is asociated to. 由于将a.genders列表配置为EAGER,因此每次选择用户时,它将获取与该用户关联的所有性别。 Even if they don't match the JPQL query. 即使它们与JPQL查询不匹配。

If you setup the a.genders list as LAZY, it wont fetch any Gender, since you selected only from User 如果您将a.genders列表设置为LAZY,则它将不会获取任何性别,因为您仅从用户中选择了

That query is equivalent to SQL 该查询相当于SQL

SELECT a.* FROM users a LEFT JOIN genders b ON a.id=b.id WHERE b.sex='dasd'

If you want to select only one Gender 如果您只选择一种性别

SELECT b FROM Gender b WHERE b.user = :user AND b.sex = 'dasd'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM