简体   繁体   中英

Criteria API not in @ElementCollection

With Permission being an enumeration, is it possible to select all users without a certain permission using JPA Criteria API:

@Entity
public class User {

    @ElementCollection
    @CollectionTable(joinColumns = @JoinColumn(name = "USER_ID"))
    private Set<Permission> permissions = new HashSet<>();

}

My current approach (returns nothing):

// em => EntityManager
// cb => CrieriaBuilder
Root<User> root = query.from(User.class);
query.select(root);
SetJoin<User, Permission> join = root.joinSet("permissions");
query.where(cb.not(cb.equal(join, Permission.RULE_THEM_ALL)));
List<User> result = em.createQuery(query).getResultList();

I ended up using a subquery to select all users with the specific permission and exclude them from the result set.

CriteriaQuery<User> query = cb.createQuery(User.class);
Root<User> root = query.from(User.class);
query.select(root);

Subquery<Long> subquery = query.subquery(Long.class);
Root<User> subroot = subquery.from(User.class);
SetJoin<User, Permission> join = subroot.join("permissions");
subquery.select(subroot.get("id")).where(cb.equal(join, Permission.RULE_THEM_ALL));

query.where(root.get("id").in(subquery).not());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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