javahibernatejpahibernate-criteria

How to create an instance of CriteriaBuilder using JPA


How to create an instance of CriteriaBuilder using JPA in a provider agnostic way? i.e. we don't want to use HibernateUtil to fetch HibernateSession

Session session = HibernateUtil.getHibernateSession();
CriteriaBuilder cb = session.getCriteriaBuilder();

Solution

  • A provider agnostic way to create instance of CriteriaBuilder in Spring Boot JPA:

    import jakarta.persistence.EntityManager;
    
    @Autowired
    private EntityManager entityManager;
    // ...
    
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();