I have JpaAdvertiseCacheRepositoryImpl which is a custom repository implementation of SpringDataJpa. I need this for a complicated criteria.
I managed to do filter criterias via Predicates and pagination via TypedQuery.
My big issue now is Sorting! Could not find a way to do this in custom implementation of repo.
Anybody knows how to do that?
Tnx
public class JpaAdvertiseCacheRepositoryImpl implements JpaAdvertiseCacheRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Override
public List<AdvertiseCacheJpa> findByFilter(FilterBuilder filter) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<AdvertiseCacheJpa> query = builder.createQuery(AdvertiseCacheJpa.class);
Root<AdvertiseCacheJpa> from = query.from(AdvertiseCacheJpa.class);
//apply filter <- applyFilter returns array of predicates
Predicate[] predicates = applyFilter(filter, builder, from);
if (predicates.length > 0) {
//query.where(builder.and(predicates));
query.where(predicates);
}
//apply sorting <- THIS HAVE TO WORK SOON :)
Sort sort = new Sort(Sort.Direction.ASC, "price");
//query.orderBy()
//apply pagination
TypedQuery typedQuery = em.createQuery(query);
typedQuery = typedQuery.setFirstResult(filter.getOffset());
typedQuery = typedQuery.setMaxResults(filter.getMaxItemsPerPage());
return typedQuery.getResultList();
//return em.createQuery(query).getResultList();
}
If AdvertiseCacheJpa model contains “price” field (it is unknown from which model it is from this part of code), should be something like this:
Also, CriteriaBuilder don’t know anything about Spring’s Sort object, so you can not use it directly here.
Instead of
use this