简体   繁体   中英

Nested JPA projection using custom query

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?

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.

You can use Hibernate ResultTransformer . This article from Vlad mihalcea presents an example of how to customize result set mappings .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM