Story
Given a Book
class and one of it's DTO class BookMeta
as shown below, create a repository method that retrieve all BookMeta
by category.
@Entity public class Book { private String title; private String author; private String category; private String intro; // getter and setters are ommitted for brevity } @Entity public class BookMeta { private String title; private String author; public BookMeta(String title, String author) { this.title = title; this.author = author; } // getter and setters are ommitted for brevity }
Solution
As part of JPA, JPQL now supports constructor expressions. What we could do is to new
a full-classpath-constructor in the named query.
@Repository public interface BookRepository extends JpaRepository<Book, Long> { @Query("SELECT new com.leafyjava.domains.dtos.BookMeta(b.title, b.author) FROM Book b WHERE b.category = :category") List<BookMeta> findAllMetaByCategory(@Param("category") String category); }
Lesson Learnt
- DTO class full classpath must be used in the
@Query
annotation - Use
@Param
to set query parameters.