我正在尝试将 oracle 结果列表绑定(bind)到摘要列表。但我的摘要列表有 3 个类定义为数据库实体
我有三个实体类A、B、C
Summary.class
{
@Autowired
private A a;
@Autowired
private B b;
@Autowired
private C c;
//getters and setters
}
@Enity
class A{
Fields 1..n ;
} // same goes for other classes definition
我通过以下查询获得结果,但结果无法转换为摘要对象
List<Summary> summaryList = entityManager.createQuery("from A a, B b, C c" +
" where a.field1 = b.field1 and a.fValue = :fValue " +
"and b.field3= c.field3", Summary.class)
.setParameter("fValue ", fValue )
.getResultList();
调试: 我确保结果列表不为空,并且如果我不将其转换为对象,下面的查询可以正常工作
List summaryList = entityManager.createQuery("from A a, B b, C c" +
" where a.field1 = b.field1 and a.fValue = :fValue " +
"and b.field3= c.field3")
.setParameter("fValue ", fValue )
.getResultList();
我看到的替代方案1是迭代summaryList并将其分配给像这样的单独列表,我还没有测试过,但我认为它可能会给出类强制转换异常,因为强制转换之前起作用
for (int i = 0; i < summaryList.size(); i++) {
Summary s= (Summary) summaryList.get(i); // might be class cast Exception
aList.add(s.getA());
bList.add(s.getB());
}
我想的替代方案2是 从 db 中仅获取 A 类字段列表,将其转换为 A 的列表,暴力执行 3 次,直到获得所有字段。
以下是我在创建新问题之前查看的一些问题
Uses a different class to combine multiple entity classes
gets a list back mapped to pojo
请让我知道您的想法,我认为我的主要方法如果有效的话是很好的方法。
最佳答案
您的 JPQL 选择语句“from A a, B b, C c”
无法映射回摘要实体,JPA 没有足够的信息来执行此操作。
如果在你的逻辑中,一个摘要实例可以由 A、B、C 组成,那么你可以有一个像
这样的构造函数
public Summary(A a, B b, C c) { ............. }
并将您的 select 语句更改为
"select new Summary(a, b, c) FROM A a, B b, C c"
关于java - 无法使用请求结果类型为具有多个返回的查询创建类型化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38107630/