Skip to content

Native SQL projection

Sometimes executing native SQL is a better choice than executing JPQL query. We may either want to execute query that is just not supported by JPQL, or just using SQL feels more natural.

Spring Data JPA has support for native SQL projections but it is limited only to interface based projections - no records, no classes.

java
interface MovieRepository {
    @Query(value = "select id, title from movie where id = :id", native = true)
    MovieSummary findById(String id);
}
java
interface MovieSummary {
    String getId();
    String getTitle();
}

Similar to JPA projections, native SQL query projections do not support one-to-many or many-to-many relations out of the box.

You can write custom repository implementation that does the mapping - similar to what Vlad Mihalcea shows in section "Fetching a hierarchical DTO projection with Spring Data JPA" of his article.

Let's stay in touch and follow me on Twitter: @maciejwalkowiak

Subscribe to RSS feed