我需要查询包含列表的对象。
@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。
答案 0 :(得分:1)
等效的JPQL可能就像这样
SELECT ua FROM UserAccount ua JOIN ua.roles r WHERE r.name = :roleName
所以Criteria就像是
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));