如何为具有多个条件和其他关系的子查询编写jpql查询

时间:2016-04-17 10:31:49

标签: postgresql jpa hql jpql

我想通过JPQL触发查询。我是JPA新手并学习JPQL但是坚持这个查询。

SELECT * FROM users
WHERE userid NOT IN (SELECT userid FROM applicants)
AND gender = 'MALE' AND (firstname like '%R%' OR lastname like '%S%');

这里性别和名称参数是动态传递的,但在这里我保持静态。

My Classes Snippets是: 这是我的用户类
用户类:

@Table(name = "users")
public class User{

@Id
@GeneratedValue
private long userId;

@Column(unique = true, nullable = false)
private String email;

private String firstName;

private String middleName;

private String lastName;

private String gender;

private Timestamp appliedOn;
}

申请者类与User类具有OneToOne关系,而join列是userid。

申请人类:

@Entity
@Table(name = "applicants")
public class Applicant{

@Id
private long applicantId;

@OneToOne
@JoinColumn(name = "userId")
private User user;

@ManyToOne
@JoinColumn(name = "subCourseId")
private SubCourse course;

@ManyToOne
@JoinColumn(name = "collegeId")
private College college;
}

2 个答案:

答案 0 :(得分:2)

通过LEFT JOIN,你想实现的目标是什么:

SELECT * FROM users
LEFT JOIN applicants ON users.userid = applicants.userid
WHERE applicants.userid IS NULL
AND gender = 'MALE' AND (firstname like '%R%' OR lastname like '%S%');

或NOT IN:

SELECT * FROM users
WHERE userid NOT IN (SELECT userid FROM applicants)
AND gender = 'MALE' AND (firstname like '%R%' OR lastname like '%S%');

如果是,您应该从那里开始找到答案。

答案 1 :(得分:0)

该SQL的JPQL查询

SELECT * FROM users
WHERE userid NOT IN (SELECT userid FROM applicants)
AND gender = 'MALE' AND (firstname like '%R%' OR lastname like '%S%');

将是下一个:

String jpql = "SELECT us FROM User us WHERE us.userId NOT IN (SELECT appl.user.userId FROM Applicant appl) AND us.gender = ?1 AND (us.firstName LIKE ?2 OR us.lastName LIKE ?3)";
Query query = entityManager.createQuery(jqpl);
query.setParameter(1, "MALE");
query.setParameter(2, "%R%");
query.setParameter(3, "%S%");
query.getResultList();