SpringDataJPA: custom data mapping with Native Query

前端 未结 2 826
被撕碎了的回忆
被撕碎了的回忆 2021-02-19 19:35
public interface UserRepository extends JpaRepository {

  @Query(value = \"SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?0\", nativeQuery = true)
  User          


        
2条回答
  •  长情又很酷
    2021-02-19 20:26

    What about interface based projection?

    Basically you write interface with getters that correspond to SQL query parameters.

    In this way you even don't need to force @Id parameter on projection:

    @Entity
    public class Book {
         @Id
         private Long id;
         private String title;
         private LocalDate published;
    }
    
    public interface BookReportItem {
         int getYear();
         int getMonth();
         long getCount();
    }
    
    public interface BookRepository extends Repository {
         @Query(value = "select " +
                        "  year(b.published) as year," +
                        "  month(b.published) as month," +
                        "  count(b) as count," +
                        " from Book b" +
                        " group by year(b.published), month(b.published)")
         List getPerMonthReport();
    }
    

    It uses org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap underneath as proxy for interface in current Spring implementation.

    It works for nativeQuery = true too.

提交回复
热议问题