public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
User findByEmailAddress(String emailAddress);
}
我们说我有上面的代码,我从用户那里选择*。如果我不希望此方法返回User对象,我该怎么办?有没有办法我可以手动将数据映射到自定义对象MyUser?我可以在UserRepository界面中完成所有这些吗?
谢谢!
答案 0 :(得分:14)
你可以做这样的事情
@Query(value = "SELECT YOUR Column1, ColumnN FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
List<Object[]> findByEmailAddress(String emailAddress);
您必须进行映射。看一下Spring Data Repository。 Source
答案 1 :(得分:0)
What about interface based projection?
基本上,您使用与SQL查询参数相对应的getter编写接口。
通过这种方式,您甚至不需要在投影上强制使用@Id
参数:
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();
}
它使用下面的org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap
作为当前Spring实现中接口的代理。
它也适用于nativeQuery = true
。