Yes, you can achieve this with forecasts. You have many ways to use them:
If you can upgrade to Spring Data Hopper, it provides convenient forecast support. Learn how to use them in the reference documentation .
Otherwise, first create a DTO with the attributes you want to load, for example:
package org.example; public class RuleProjection { private final Long id; private final String name; public RuleProjection(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public String getName() { return name; } }
Of course, you can also use Lombok annotations.
Then you can use in JPQL queries, for example:
select new org.example.RuleProjection(rule.id, rule.name) from RuleVO rule order by rule.name
Another option, if you want to avoid using DTO class names in your queries, is to implement your own query method using QueryDSL. With Spring JPA data, you should:
Create a new interface using the new method. Example:
public interface RuleRepositoryCustom { public List<RuleProjection> findAllWithProjection(); }
Modify your repository to expand the new interface. Example:
public interface RuleRepository extends JpaRepository<RuleVO, Long>, RuleRepositoryCustom { ...
Create a custom repository implementation using JPA support. You must pre-generate Q clases QueryDSL using its Maven plugin. Example:
public class RuleRepositoryImpl { public List<RuleProjection> findAllWithProjection() { QRuleVO rule = QRuleVO.ruleVO; JPQLQuery query = getQueryFrom(rule); query.orderBy(rule.name.asc()); return query.list(ConstructorExpression.create(RuleProjection.class, rule.id, rule.name)); } }
source share