Search code examples
spring-data-jparecord

Use Record Class with select new spring data jpa


Is it possible to use record as return type with select new syntax in spring data jpa query ?

Something like this:

@query("select new path-to-my-record.MyRecord(...)
List<MyRecord> myQuery(...)

Solution

  • Yes, starting from spring-boot-starter-data-jpa:3.0.4 you can use Java records within JPQL queries. See https://www.baeldung.com/spring-jpa-java-records for use-cases.

    Example:

    // your entity
    @Entity
    @Table(name = "book")
    public class Book {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String title;
        private String author;
        private String isbn;
        
        // constructors, getters, setters
    }
    
    // corresponding record
    public record BookRecord(Long id, String title, String author, String isbn) {}
    
    // repository. You can use both named queries and `@Query` annotation
    public interface BookRepository extends JpaRepository<Book, Long> {
    
      List<BookRecord> findBookByAuthor(String author);
    
      @Query("SELECT new com.full.package.name.BookRecord(b.id, b.title, b.author, b.isbn) FROM Book b WHERE b.id = :id")
      BookRecord findBookById(@Param("id") Long id);
    }