java 如何在 Hibernate 5.2 之后使用 `setResultTransformer`?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38240015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use `setResultTransformer` after Hibernate 5.2?
提问by blackdog
I wanna use query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
to get a List<Map>
. But I got a exception:
我想用query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
得到一个List<Map>
. 但我有一个例外:
java.lang.NoSuchMethodError: org.hibernate.query.Query.setResultTransformer(Lorg/hibernate/transform/ResultTransformer;)Lorg/hibernate/Query;
I can't find the implemented class of org.hibernate.query.Query
.
The method setResultTransformer
is in org.hibernate.Query
.
我找不到org.hibernate.query.Query
. 该方法setResultTransformer
在org.hibernate.Query
.
And why is the org.hibernate.Query deprecated?
为什么不推荐使用 org.hibernate.Query?
采纳答案by ali akbar azizkhani
The ResultTransformer comes with a legacy definition which is not following the Functional Interface syntax. Hence, we cannot use a lambda in this example. Hibernate 6.0 aims to overcome this issue, so that's why the Hibernate ORM 5.2 ResultTransformer is deprecated. Nevertheless, an alternative will be provided, so the concept we are discussing in this article is going to stand still even in Hibernate 6.
ResultTransformer 带有不遵循功能接口语法的遗留定义。因此,我们不能在这个例子中使用 lambda。Hibernate 6.0 旨在克服这个问题,这就是 Hibernate ORM 5.2 ResultTransformer 被弃用的原因。然而,将提供替代方案,因此我们在本文中讨论的概念即使在 Hibernate 6 中也将保持不变。
回答by HappyFace
Don't use session.createQuery(hql,transformerClass);
if you select multiple items in your query, use the old deprecated method instead.
session.createQuery(hql,transformerClass);
如果您在查询中选择多个项目,请不要使用,而是使用旧的已弃用方法。
回答by Ranjeet Rana
Since Hibernate 5.2 uses Java 8 you can use stream api
由于 Hibernate 5.2 使用 Java 8,您可以使用流 api
List<EmployeeDto> resultList = session
.createQuery(" from Employee", Employee.class)
.stream()
.map((employee) -> {
return new EmployeeDto(employee);
})
.collect(Collectors.toList());
This code will also give some performance improvement.
此代码还将提供一些性能改进。