gpt4 book ai didi

Spring Boot setResultTransformer 和 addScalar

转载 作者:行者123 更新时间:2023-12-05 05:13:01 25 4
gpt4 key购买 nike

我在使用 entityManager 对象返回查询结果集时遇到问题。我想返回应该转换为 pojo 对象的连接查询。

经过多次尝试,我找到了下面的工作代码

public List<Test> getData() {

Query a = entityManager.createNativeQuery("select t1.data1,t2.data2 from test1 t1 join test2 t2 on t1.id = t2.id");
a.unwrap(SQLQuery.class)
.addScalar("data1", LongType.INSTANCE)
.addScalar("data2", DoubleType.INSTANCE)
.setResultTransformer(Transformers.aliasToBean(Test.class));

return a.getResultList();
}

但我收到警告,setResultTransformer()addScalar() 方法已弃用。
任何人都可以把它的替代代码或请提供解决方案。
谢谢。

最佳答案

1) 首先弃用的是 SQLQuery :

(since 5.2) use NativeQuery instead.

2) 但它不会解决您的问题,因为 SQLQuery.addScalar() org.hibernate.query.Query.setResultTransformer()如您所见,也已弃用。
From the Hibernate 5.3 migration guide :

With a ResultTransformer it is possible to define how the results of a query should be handled, i.e., it can be used to change the "shape" of the query results.

In Hibernate 6.0, the ResultTransformer will be replaced by a @FunctionalInterface and for this reason, the setResultTransformer() method in org.hibernate.query.Query is deprecated.

There is no replacement for ResultTransformer in Hibernate 5.3, therefore as recommended here, for the moment it can be used as-is.

因此您可以保留它并通过添加 TODO 注释来抑制警告。

@SuppressWarnings("deprecation")
public List<Test> getData() {

Query a = entityManager.createNativeQuery(
"select t1.data1,t2.data2 >from test1 t1 join test2 t2 on t1.id = t2.id");
a.unwrap(NativeQuery.class)
// TODO warning to remove with Hibernate 6 for addScalar()
.addScalar("data1", LongType.INSTANCE)
.addScalar("data2", DoubleType.INSTANCE)
// TODO warning to remove with Hibernate 6 for setResultTransformer()
.setResultTransformer(Transformers.aliasToBean(Test.class));

return a.getResultList();
}

关于Spring Boot setResultTransformer 和 addScalar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54060781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com