Home > Back-end >  JPA Criteria API does Set contain the value?
JPA Criteria API does Set contain the value?

Time:11-16

Imagine a library. The library contains books. Each book is a separate entity. There are readers (peoples) in the library. When a person takes a book to read, I indicate that this book was read by people.

The subject area has been redesigned for the question, don't swear off the logic

I can't understand how to make a Criteria query to see if Set<People> peoples contains people of a certain People

@Entity
@Table(name = "book")
public class Book{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @Column
    @NotEmpty
    String title;

    @ManyToMany(cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE
    })
    @JoinTable(name = "people_read",
            joinColumns = @JoinColumn(name = "id_people"),
            inverseJoinColumns = @JoinColumn(name = "id_book"))
    Set<People> peoples = new HashSet<>();
}
@Getter
@Setter
@Entity
@Table(name = "people")
public class People {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @Column
    @NotEmpty
    String name;

    @ManyToMany(mappedBy = "peoples")
    Set<Book> books = new HashSet<>();
}

What I'm trying to do:

Path<Object> peoples = root.get("peoples");
(Predicate) query.where(peoples .get("id").in(cb.parameter(Set.class, "3"))); //3 is for example the id of people whom I want to know if they have read the book

CodePudding user response:

I don't know how to write this query checking the Id only, but if you have an Instance of People the query would look like this

query.where(cb.isMember(peopleInstance, root.get("peoples"))

  • Related