3 回答
TA贡献1891条经验 获得超3个赞
这种投影有更好的替代方案,而不是默认的Object[]。
您可以使用 JPAjavax.persistence.Tuple结果集,因为Hibernate ORM 5.2.11适用于本机 SQL:
List<Tuple> postDTOs = entityManager
.createNativeQuery(
"SELECT " +
" p.id AS id, " +
" p.title AS title " +
"FROM Post p " +
"WHERE p.created_on > :fromTimestamp", Tuple.class)
.setParameter( "fromTimestamp", Timestamp.from(
LocalDateTime.of( 2016, 1, 1, 0, 0, 0 )
.toInstant( ZoneOffset.UTC ) ))
.getResultList();
您可以使用 Hibernate-specific ResultTransformer,它允许您构建非常复杂的 DTO 结构(例如图形):
List postDTOs = entityManager
.createNativeQuery(
"select " +
" p.id as \"id\", " +
" p.title as \"title\" " +
"from Post p " +
"where p.created_on > :fromTimestamp")
.setParameter( "fromTimestamp", Timestamp.from(
LocalDateTime.of( 2016, 1, 1, 0, 0, 0 ).toInstant( ZoneOffset.UTC ) ))
.unwrap( org.hibernate.query.NativeQuery.class )
.setResultTransformer( Transformers.aliasToBean( PostDTO.class ) )
.getResultList();
您还可以使用命名的本机查询:
List<PostDTO> postDTOs = entityManager
.createNamedQuery("PostDTO")
.setParameter( "fromTimestamp", Timestamp.from(
LocalDateTime.of( 2016, 1, 1, 0, 0, 0 )
.toInstant( ZoneOffset.UTC ) ))
.getResultList();
其中PostDTO查询是一个命名的本机 SQL 查询,如下所示:
@NamedNativeQuery(
name = "PostDTO",
query =
"SELECT " +
" p.id AS id, " +
" p.title AS title " +
"FROM Post p " +
"WHERE p.created_on > :fromTimestamp",
resultSetMapping = "PostDTO"
)
@SqlResultSetMapping(
name = "PostDTO",
classes = @ConstructorResult(
targetClass = PostDTO.class,
columns = {
@ColumnResult(name = "id"),
@ColumnResult(name = "title")
}
)
)
酷,对吧?
TA贡献1856条经验 获得超17个赞
只需通过调用创建它
createNativeQuery("SELECT a.a, a.b, a.c FROM aTable");
它将默认返回一行Object[]
.
该警告与您的情况无关,因此只需将其压制即可。
添加回答
举报