SpringDataJPA:使用 Native Query 自定义数据映射
SpringDataJPA: custom data mapping with Native Query
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
User findByEmailAddress(String emailAddress);
}
假设我有上面的代码,其中我 select * 来自用户。不想这个方法到returnUser对象怎么办。有没有办法可以手动将数据映射到自定义对象 MyUser?我可以在 UserRepository 界面中完成所有这些吗?
谢谢!
你可以这样做
@Query(value = "SELECT YOUR Column1, ColumnN FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
List<Object[]> findByEmailAddress(String emailAddress);
你必须做映射。也看看 Spring 数据存储库。 Source
What about interface based projection?
基本上,您使用对应于 SQL 查询参数的 getter 编写接口。
通过这种方式,您甚至不需要在投影上强制使用 @Id
参数:
@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();
}
它在当前 Spring 实现中使用下面的 org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap
作为接口的代理。
它也适用于 nativeQuery = true
。
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
User findByEmailAddress(String emailAddress);
}
假设我有上面的代码,其中我 select * 来自用户。不想这个方法到returnUser对象怎么办。有没有办法可以手动将数据映射到自定义对象 MyUser?我可以在 UserRepository 界面中完成所有这些吗?
谢谢!
你可以这样做
@Query(value = "SELECT YOUR Column1, ColumnN FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
List<Object[]> findByEmailAddress(String emailAddress);
你必须做映射。也看看 Spring 数据存储库。 Source
What about interface based projection?
基本上,您使用对应于 SQL 查询参数的 getter 编写接口。
通过这种方式,您甚至不需要在投影上强制使用 @Id
参数:
@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();
}
它在当前 Spring 实现中使用下面的 org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap
作为接口的代理。
它也适用于 nativeQuery = true
。