Hibernate JPA 条件查询

Hibernate JPA Criteria Query

我需要查询一个包含列表的对象。

@Entity
@Table(name = "userAccount")
public class UserAccounts implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

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

@Column(name = "hash", nullable = false, length = 60)
private String hash;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "userID"), inverseJoinColumns = @JoinColumn(name = "roleID"))
private List<Role> roles;

@Enumerated(EnumType.ORDINAL)
private Status status;

//getters and setters
}

我需要获取包含角色 "ROLE_USER" 的对象。 我如何使用 CriteriaBuilder 实现这一目标?

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<UserAccounts> cq = cb.createQuery(UserAccounts.class);
    Root<UserAccounts> ua = cq.from(UserAccounts.class);

我应该在这里放什么?

//      cq.where(cb.and(cq.equals(ua.get("roles")),
//      cq.equals(ua.get("status"), Status.ACTIVE)));

TIA。

等效的 JPQL 可能是这样的

SELECT ua FROM UserAccount ua JOIN ua.roles r WHERE r.name = :roleName

所以标准应该是这样的

Join<UserAccounts, Role> roleRoot = ua.join(UserAccounts_.roles);
roleRoot.alias("r");
ParameterExpression<String> param = qb.parameter(String.class);
cq.where(roleRoot.get(Role_.name).equals(param));