SpringDataJPA: custom data mapping with Native Query

前端 未结 2 809
被撕碎了的回忆
被撕碎了的回忆 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<Book, Long> {
         @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<BookReportItem> 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.

    0 讨论(0)
  • 2021-02-19 20:37

    You can do something like this

    @Query(value = "SELECT YOUR Column1, ColumnN FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
    List<Object[]> findByEmailAddress(String emailAddress);
    

    You have to do the mapping. Take a look at the Spring Data Repository as well. Source

    0 讨论(0)
提交回复
热议问题