Hibernate HQL在对象中实例化对象

时间:2018-04-14 16:09:44

标签: java spring hibernate hql

注意:不使用现实生活中的示例,而是直接在stackoverflow上输入我的情况的“模拟”,所以请忽略语法错误。

假设我有2个班级,其中A是B的一对多。忽略缺少getter / setter

class A {
    private int a;
    private int b;
    private List<B> kids;

    public A() {}
    public A(int a, int b) { this.a = a; this.b = b; }
}
class B {
    private int c;
    private int d;
    private A parent;

    public B() {}
    // what I'd like to use:
    public B(int c, int d, A a) { this.c = c; this.d = d; this.parent = a; }
    // current workaround:
    public B(int c, int d, int a, int b) {
        A pr = new A(); pr.setA(a); pr.setB(b);
        this.c = c; this.d = d; this.parent = pr;
    }
}

目标是创建一个String查询,该查询将查询A和B并获得一个只有query.list()被调用(没有设置后)的全部对象

HQL是如何表达的,我知道你可以做类似的事情:

select new A(a.column_1, a.column_2) from A a;

使用HibernateTemplateQuery使用query.list()即可立即获得实例化的A对象。

我的问题是我是否可以在另一个实例化中实例化?像

这样的东西
select new B(b.column_1, b.column_2, new A(a.column_1, a.column_2)) 
from A a, B b where a.a_id = b.a_id;

并实际使用我在上面标记为“首选”构造函数的构造函数。 当我尝试使用上面的方法时,我得到了一个例外:

antlr.NoViableAltException: unexpected token: A

目前我唯一的解决方法是使用其他“替代方法”构造函数,其查询类似于:

select new B(b.column_1, b.column_2, a.column_1, a.column_2) 
from A a, B b where a.a_id = b.a_id;

主要问题是,我想要的甚至可能吗?如果有,怎么样? :)

谢谢,如果您对我的问题有任何疑问,请拍!

谢谢!

0 个答案:

没有答案
相关问题