I'm new to Spring Data projection and I'm trying to use this feature in a new project.
In particular I'd like to use projections on a repo method associated to a complex query.
I annotated my method with the @Query
annotation and declared a JPA query with several joined tables/entities and a complex where condition.
In this article I read that is possible to use an interface-based projection and a class-based projection, but only the first one supports nested projections.
I need nested projection but it seems that this feature is only supported using interface-based projections, and this approach is only possible with auto-generated query methods and not using explicit JPA queries. Is this right?
Is there a way to use interface-based projections using custom JPA queries?
CodePudding user response:
You can use interface projections with custom queries. If this is the interface:
public interface MyView {
int getCount();
String getName();
}
Then you can make a query like this:
@Repository
public interface MyRepository extends JpaRepository<Entity, Long> {
@Query("SELECT e.some_count AS count, e.name FROM Entity AS e WHERE e.id IN :ids")
List<MyView> findViews(List<Long> ids);
}
Interface projections work with custom queries, be it JPA or native. Just the column name must match method name, as in example. I have not used nested projections yet, but i don't see a reason why they wouldn't work.
Also found this question about nested projections, which should help.
CodePudding user response:
You can use Hibernate ResultTransformer , this article from Vlad mihalcea present an example of how customize result set mappings