Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

java - Why left join on CriteriaQuery doesn't filter results?

I have two entities, User and Roles each one with active boolean parameter and ManyToMany relationship.

This boolean parameter is used for logical delete.

Why does the result include inactive Roles when I run this query below?

 CriteriaBuilder builder = em.getCriteriaBuilder();
 CriteriaQuery<User> query = builder.createQuery(User.class);

 //Select
 Root<User> user = query.from(User.class);

 //Join
 SetJoin<User, Role> role = user.joinSet("roles", JoinType.LEFT);
 Predicate rolesActivePredicate = builder.isTrue(role.get("active"));
 role.on(rolesActivePredicate);

 query.multiselect(user).distinct(true);

 //Where
 Predicate usernamePredicate = builder.equal(user.get("username"), username);
 Predicate activePredicate = builder.isTrue(user.get("active"));
 query.where(usernamePredicate, activePredicate);

 TypedQuery<UnikUser> typedQuery = em.createQuery(query);
 return Optional.of(typedQuery.getSingleResult());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. Consider the following Users with @OneToMany relationship to Roles.
 User-1 : Active-Role-1, Active-Role-2, In-Active-Role-3
 User-2 : In-Active-Role-3
 User-3 : Active-Role-1, Active-Role-2
  1. JPA first finds User records that satisfy your condition (have at-least one an active role)
 User-1
 User-3
  1. This is where the role of your where conditions end. Once it has been decided which record id to fetch, JPA will fetch those User records in full. User-1 and User-3 with all their associated roles (including inactive). It might do join or another select but whenever it does, it will fetch all of its associated fields

  2. In summary, Once it has decided to fetch an entity, it cannot do any filtering on its associated fields. In this case, you expected a filtered objects in user.getRoles() but it cannot.

  3. If JPA had allowed that, it cannot do dirty checking, cascading or repeatable read. So it does not allow it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...