我有JPA实体,其中包含以下字段:
@ManyToMany
@JoinTable(name = "user_organization",
joinColumns = { @JoinColumn(name = "USER_ID") },
inverseJoinColumns = { @JoinColumn(name = "ORGANIZATION_ID") })
@LazyCollection(LazyCollectionOption.FALSE)
@SortNatural
private SortedSet<Organization> organizations = new TreeSet<Organization>();
给定Organization
个对象(myOrgs)列表并使用CriteriaBuilder,如何编写一个条款来说明:
给我所有
User
个对象中至少有一个Organization
的对象myOrgs
变量?
我尝试了以下但没有成功......
final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
final CriteriaQuery<User> criteria = builder.createQuery(User.class);
final Root<User> userRoot = criteria.from(User.class);
criteria.where(builder.isMember(myOrgs, userRoot.get(User_.organizations)), ...
我正在使用JPA 2.1和Hibernate 4.3.6.Final。
答案 0 :(得分:0)
早上好,我会尝试以下操作:
//GET A LIST OF IDS
List<Long> orgsIds = new ArrayList<>();
for (Organization org : myOrgs){
orgsIds.add(org.getId());
}
//CREATE QUERY WITH JOIN AND NOT FINAL
CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
CriteriaQuery<User> criteria = builder.createQuery(User.class);
Root<User> userRoot = criteria.from(User.class);
Join<User,Organization> organizationJoin = userRoot.join(User_.organizations,JoinType.INNER)
//DISTINCT BECAUSE JOIN WITH MULTIPLE ORGs RETURN REPEATED RESULTS
criteria.select(cb.distinct(userRoot));
criteria.where(organizationJoin.get(Organization_.id).in(orgsIds));
JPA 2.1中新增的一个更有效的选项是在联接中添加另一个条件,如下所示:
Join<User,Organization> organizationJoin = userRoot.join(User_.organizations,JoinType.INNER);
organizationJoin.on(cb.and(organizationJoin.get(Organization_.id).in(orgsIds)));
并删除where子句