2

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

This is now deprecated. See docs.jboss.org/hibernate/orm/6.0/javadocs/org/hibernate/…. Use TupleTransformer and/or ResultListTransformer instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.