Two methods of querying when jpa implements many to many attributes

  • 2021-12-13 07:57:02
  • OfStack

Directory jpa many-to-many attribute query 1: JPQL method 2: specification method JPA, HQL many-to-many query statement Hql statement another writing method

jpa Many-to-Many Attribute Query

1: Adopt JPQL mode

Use @ Query to splice jpql statement to complete many-to-many query;


@query ( 
SELECT User FROM User u JOIN Student s on s.id = u.id where u.name LIKE :name
 ) 
User findallByName(@param( " name " )String name);

Second: Adopt specification method

List in user < student > Attributes, many-to-many relationships;

The code is as follows:


   Specification<Class> specification = new Specification<>(){
   @override
   public predicate toPredicate(Root<Class> root , CriteriaQuery<?> query ,CriteriaBuilder cb){
       List<Precidate> precidate = Lists.newArrayList<>();
       if(num>0){
       Predicate p1 = cb.equal(root.get("num").as(Integer.Class),count);
         precidate.add(p1);
       }
       if(channel > 0){
         ListJoin<User,Student> join= root.join(root.getModel().getList("student",student.class),JoinType.LEFT);
         Predicate p2 = cb.equal(join.get("id").as(Integer.Class));
         // In here join It represents the student Belonging to the added part, not the whole result of the linked table; 
         precidate.add(p2);
       }
       List<User> list = DAO.findAll(specification,new Sort(DESC,"id"));
}
}

JPA, HQL Many-to-Many Query Statement

One teacher teaches many students, one student is taught by many teachers, one student has many books, and the same kind of books are owned by many students.

Ask the teacher who teaches students who own the book a!

Hql statement


SELECT t FROM Teacher t join t.students s join s.books b where b.name = 'a' 

Explanation: s in t. students s does not mean collection, but the table alias of students object of t. join t. students s, hql and hibernate will be translated into the internal join relationship between two tables

Wrong writing:


SELECT t FROM teacher t where t.students.books.name = 'a' 

In fact, the reason is obvious. t. students is an Set, so how can this Set have the attribute of books? Similarly, books. name is also wrong, so the inter-table join is used and the alias t. students s is given. At this time, the object s has books attribute, so you can write s. books b, and finally use b. name to restrict the query b. name = 'a'.

Another way of writing


SELECT t FROM Teacher t,Student s,Book b where s.id in elements(t.students) and b.id in elements(s.books)

There is nothing wrong with this method! However, this way to use subqueries!


Related articles: