简体   繁体   中英

JPA. Filter entities where a field Set<> contains certain value

I have an entity where one of fields is <Set> groups.

@Entity
public class TimetableItem {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
    
        /*different fields */
    
   @ManyToMany
   @JoinTable(name = "timetable_items_groups",
              joinColumns = @JoinColumn(name = "timetable_item_id"),
              inverseJoinColumns = @JoinColumn(name = "group_id"))
  private Set<Group> groups;

I need to get all timetable items where the Set contains a certain group (Set can have a lot of different groups too. And if "my group" is one of them - it's that I need).

public List<TimetableItem> findItemsWithGroup(Group group) {
   CriteriaBuilder cb = em.getCriteriaBuilder();
   CriteriaQuery<TimetableItem> query = cb.createQuery(TimetableItem.class);
   Root<TimetableItem> root = query.from(TimetableItem.class);

   //something like that but it doesn’t work
   Predicate predicateForGroup = cb.isTrue(root.get(TimetableItem_.GROUPS).in(group));

   query.where(predicateForGroup);
List<TimetableItem> timetableItems = em.createQuery(query).getResultList();

If I run the code without any conditions, I can see in debugger that my List<TimetableItem> timetableItems has all items from database and each of them has Set<Group> with groups inside it.

Screenshot

Of course, I can find the items which I need “manually” (with.stream() for example) but I'm sure there is some way to get it using predicate.

Use the CriteriaBuilder.isMember-Method:

Predicate predicateForGroup = cb.isMember(group, root.get(TimetableItem_.GROUPS));

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