0

Is it possible to map the results of a Hibernate @Query like this (in a @Repository interface extending @JpaRepository):

@Query("select u.id, u.email, u.status from user u")
public SimpleUserDTO getAllUsersSimpleData();

directly to a Java object like this:

public class SimpleUserDTO {
    private Long id;
    private String email;
    private String status;
}

What I know, is that doing something like this:

Query query = session.createQuery("select u.id, u.email, u.status from user u");

the result can be extracted to a List<Object[]>:

List<Object[]> users = (List<Object[]>) query.list();

But is it possible to map it directly to a List<SimpleUserDTO> without writing additional method that will map the values to SimpleUserDTO?

1
  • Have you tried Hibernate Projections? Or the Interface-Based Projections of Spring? Commented Apr 1, 2020 at 7:14

1 Answer 1

3

You have two options.

Option 1: Constructor Expression:

@Query("select new <insert_package_here>.SimpleUserDTO(u.id, u.email, u.status) from user u")
public List<SimpleUserDTO> getAllUsersSimpleData();

Option 2: Use Interface projection

Turn your DTO into an interface and you can use it without @Query annotation

public List<SimpleUserDTO> getAllUsersSimpleData();

Please find out more about projections and Spring Data JPA in the documentation:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

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

3 Comments

I have simplified the code, but in reality, the query looks like this: select u.id, u.email, u.status, a.postalCode from user u join address a on (u.id = a.user_id) - so it includes another table. Will this also work?
Why don't you try?
Trying now the solution using projection ;)

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.