My project is Spring-boot + Spring-data-jpa + hibernate + ehcache. The 2nd level cache works with the followings:
- extends JpaRepository
2a. it works with my HQL query with query.setHimt("org.hibernate.cacheable", true);
It does not work if
- I wrap the result with other class, for example Page<>
2b. If I use Specification and Criteria to query instead of HQL
My setup are the same for both 2a and 2b. Let say my entity class is City. I use Specification like this:
CriteriaBuilder build = em.getCriteriaBuilder();
CriteriaQuery<City> query = build.createQuery(City.class);
Root<city> root = query.from(City.class);
query.where(spec.toPredicate(root,query,build));
TypedQuery<City> tq = em.createQuery(query);
tq.setHint("org.hibernate.cacheable", true);
return tq.getResultList();
The result set is correct, same list of objects as HQL. But if I call this method in a loop, it retrieves from database every time.
I don't understand, both HQL and specification generate a TypedQuery<>. Can I cache specification query using Hibernate and ehcache?