public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
User findByEmailAddress(String emailAddress);
}假设我有上面的代码,其中我选择了* from user。如果我不想让这个方法返回User对象,我该怎么办?有没有办法可以手动将数据映射到自定义对象MyUser?我可以在UserRepository界面中完成所有这些操作吗?
谢谢!
发布于 2015-11-14 05:37:41
你可以这样做
@Query(value = "SELECT YOUR Column1, ColumnN FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
List<Object[]> findByEmailAddress(String emailAddress);你必须做映射。还可以看看Spring Data Repository。Source
发布于 2018-11-15 05:36:22
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();
}它使用底层的org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap作为当前Spring实现中接口的代理。
它也适用于nativeQuery = true。
https://stackoverflow.com/questions/33701905
复制相似问题