Dynamic queries in Spring Data JPA
How can I implement dynamic queries in Spring Data JPA ? For example, there is a huge filter and not the fact that some field will not be null. Any ideas ? Thank you.
3
Author: Andrey Sibirkin, 2016-09-07
3 answers
You can wrap query parameters in specifications and pass them to queries.
Example of a request with a specification:
CuVotercntByCuSpecification builder = new CuVotercntByCuSpecification();
Specification<CuVotercntByCu> specification =
where(builder.isEqualViborrefererDate())
.and(builder.fetch("ciuSubject"))
.and(builder.fetch("viboryrefer"))
.and(builder.fetch("protocolStatus"));
List<CuVotercntByCu> allCiu = votercntByCuRepository.findAll(specification,
Sort.by("viboryrefer.namvibor", "numokr"));
Example of creating a specification:
public class CuVotercntByCuSpecification extends BaseSpecification<CuVotercntByCu> { }
2
Author: haste, 2020-09-15 16:28:19
Use em.createNativeQuery
or @SqlResultSetMapping
example here https://javastudy.ru/spring-data-jpa/jpa-native-query/
1
Author: haste, 2020-09-01 03:54:18
An example of a native query in building a dynamic query.
case Role.CIK:
if (StringUtils.hasText(reqParam.getCiuSubject())) {
sql += " AND cnt.vccucode_Subj = :ciuSubject ";
query.setParameter("ciuSubject", reqParam.getCiuSubject());
}
Query query = em.createNativeQuery(sql, CuVotercntByCu.class);
return query.getResultList();
0
Author: haste, 2020-09-18 05:27:19