Spring JPA. How to map from @Query(nativeQuery = true) to a POJO

Viewed 5072

Have a query, let it be

select 1 "colName"

I want to map the result to a POJO type using Spring Data JPA.

Thus the picture is:

public interface MyAwesomeSuperInterface extends CrudRepository {
    @Query(value = "select 1 \"colName\"", nativeQuery = true)
    List<POJO> something();
}

And the question is HOW to map it to the POJO.class?

Following the common suggestions I assume I'll get:

  1. No, I don't want to change it to JSQL and do a 'new POJO'.
  2. Why? Because I have a complex sql query, which isn't reflectable to JSQL.
  3. No, I will not bring up the query. I merely want to know how to map the upper example to a POJO using Spring Data. Thank you
2 Answers

You can use DTO projection with native queries:

// Projection Interface
public interface UserProjection {
    String getName();
    String getEmail();
    Integer getId();
    String getComment();
}

public interface UserRepository extends CrudRepository<User, Integer> {
    @Query(value = "select  u.name, u.email, c.comment from User u join 
                    Comment c on u.id = c.user_id where u.id in :ids", nativeQuery = true)
        List<UserProjection> getUserInterface(List<Integer> ids);
    }

This is one example I recently tried with DTO projections. This will Simply map result of the native query to UserProjection. For more information read: Spring Data JPA Projection support for native queries

It should auto-convert from sql query to pojo you need to define the correct datatype in below example I am using List<User> as the query will return all the data from the table :

@Query("select * from User u")
List<User> findUsers();

If you specify columns then you need to specify constructor in pojo which accepts the same fields.

You can also use parameterized query :

@Query("select * from User u where u.user_id =: userId")
List<User> findUserById(@Param("userId") String userId);

You can also refer to this document : https://www.baeldung.com/spring-data-jpa-query

it will work hoping for good.

Related