How to use Criteria Queries in Spring Boot Data Jpa Application

前端 未结 6 537
死守一世寂寞
死守一世寂寞 2020-12-04 23:10

I have an application that uses Spring Boot Data jpa . So far i am using a repository like this

public interface StudentRepository extends CrudRepos         


        
6条回答
  •  攒了一身酷
    2020-12-04 23:53

    According to Spring doc HibernateTemplate:

    NOTE: Hibernate access code can also be coded in plain Hibernate style. Hence, for newly started projects, consider adopting the standard Hibernate style of coding data access objects instead, based on SessionFactory.getCurrentSession(). This HibernateTemplate primarily exists as a migration helper for Hibernate 3 based data access code, to benefit from bug fixes in Hibernate 4.x.

    While according to Hibernate doc:

    New development should focus on the JPA javax.persistence.criteria.CriteriaQuery API. Eventually, Hibernate-specific criteria features will be ported as extensions to the JPA javax.persistence.criteria.CriteriaQuery.

    So its better to use JPQL Criteria:JPA Criteria API Queries

    Example:

      CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    
      CriteriaQuery q = cb.createQuery(Country.class);
      Root c = q.from(Country.class);
      q.select(c);
    

    where entityManager should be @Autowired. For detail info, see above link

提交回复
热议问题