Criteria in spring data

I am working on a web application using angular js, spring mvc and spring jpa data. I am wondering if there is something similar to criteria and detachedcriteria (hibernate) for making advanced queries with spring jpa data.

+3


source to share


4 answers


Yes, you can use Specifications , which mostly uses the criteria API (obviously, since Spring Data JPA is just a wrapper around JPA).



+3


source


Nothing prevents you from using the criteria



@Repository
public interface FooRepository extends JpaRepository<Foo, Long>, FooRepositoryCustom {

}

interface FooRepositoryCustom {

    public List<Foo> findByBar(Bar bar);
}

class FooRepositoryImpl implements FooRepositoryCustom {

    @PersistenceContext
    protected EntityManager em;

    @Transactional(readOnly = true)
    public List<Foo> findByBar(Bar bar) {

        Criteria crit = em.unwrap(Session.class).createCriteria(Foo.class);

        crit.add(Restrictions.eq("name", bar.getName()));

        ...

        crit.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);

        List<Foo> foos = crit.list();

        return foos;

    }
}

      

+4


source


you can use the Query a Dsl , it is less detailed than that Specification

, there is the blog , containing both Specification

, and so QueryDsl

.

+1


source


You can use criteria with Spring Data, you don't need a custom repository, you can use JpaSpecificationExecutor, here's an example:

Your repository:

@Repository("yourRepository")
public interface YourRepository extends JpaRepository, JpaSpecificationExecutor
{
}

      

Your service

@Override
public List<YourModel> yourDataModel getAllEntitiesByAttr(String attrValue){
    List<YourModel> yourDataModel = null;
    try {
     Specification specification=getAndSpecByAttribute("attribute",attrValue);
     List list = userRepository.findAll(specification);
     yourDataModel =orikaMapper.mapAsList(list, YourModel.class);
    } catch (Exception e) {
     throw e;
    }
    return yourDataModel;
}
private Specification getAndSpecByAttribute(String attribute, String valueAttribute){
 return new Specification() {
      @Override public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
        Path path = root.get(attribute);
       return cb.equal(path, valueAttribute);
      };
    };
}

      

Enough.

0


source







All Articles