I'm working on a web application using angular js, spring mvc and spring jpa data. I'm wondering if there is something similar to criteria and detachedcriteria(hibernate) to build advanced queries with spring jpa data.
Asked
Active
Viewed 8,191 times
3
-
possible duplicate of [Dynamic spring data jpa repository query with arbitrary AND clauses](http://stackoverflow.com/questions/28874135/dynamic-spring-data-jpa-repository-query-with-arbitrary-and-clauses) – iamiddy Jun 01 '15 at 15:00
4 Answers
4
Nothing stops you from still using 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;
}
}

wesker317
- 2,172
- 1
- 16
- 11
3
Yes, you can use Specifications, which basically uses the Criteria API (obviously, since Spring Data JPA is just a wrapper around JPA).

dunni
- 43,386
- 10
- 104
- 99
-
what's the best way to save an object that make reference to 2 other objects ? how to do that with only one query. (without retriving them from data base). – housseminfo Jun 01 '15 at 13:57
-
You should ask this as a new question (and accept my answer, if it helps you for the first question). – dunni Jun 01 '15 at 13:58
-
Also you should read http://stackoverflow.com/help, especially the part "Asking". – dunni Jun 01 '15 at 13:59
1
you can use Query Dsl
, it is less verbose than Specification
, here is a blog containing both Specification
and QueryDsl
.

Rafik BELDI
- 4,140
- 4
- 24
- 38
0
You can use Criteria with Spring Data, you don't need a Custom Repository, You could use JpaSpecificationExecutor, here 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);
};
};
}
It is enough.

Mayte Espi Hermida
- 19
- 3