一旦它可用于您的持久层,使用@ConstructorResult
将非常有用。在那之前,有一种特定于 Hibernate 的方法使用 anorg.hibernate.SQLQuery
和 an org.hibernate.transform.ResultTransformer
,它不依赖于@SqlResultSetMapping
. 因为一个 POJO 被填充,Hibernate 发现没有@Entity
自动变成一个表。
非持久 POJO:
public class Foo {
public Long row_id;
public String name;
}
结果转换器:
public static class FooResultTransformer implements ResultTransformer {
@Override
public List transformList(List list) { return list; }
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
List<String> aliasList = Arrays.asList(aliases);
Foo foo = new Foo();
foo.row_id = ((Number) getValue(tuple, aliasList, "row_id", 0L))
.longValue();
foo.name = (String) getValue(tuple, aliasList, "name", null);
return foo;
}
private static Object getValue(Object[] tuple, List<String> aliases,
String field, Object defaultValue)
{
// unchecked for berevity
if (tuple[aliases.indexOf(field)] == null) {
return defaultValue;
}
return tuple[aliases.indexOf(field)];
}
}
本机 SQL 查询:
String sql = "SELECT id AS row_id, friendlyName AS name FROM SomeTable";
Session session = JPA.em().unwrap(Session.class);
SQLQuery q = session.createSQLQuery(sql);
q.setResultTransformer( new FooResultTransformer() );
List<Foo> fooList = q.list();