在我的Oracle数据库中,我有两个示例表:
A
列id
,a1
,a2
,a3
B
列id
,b1
,b2
,b3
我有从这两个表中获取信息的观点:
CREATE VIEW Foo ("A.id", "A.a1", "A.a2", "A.a3", "B.id", "B.b1", "B.b2", "B.b3") AS
SELECT aaa.*, bbb.*
FROM A aaa, B bbb
WHERE
...some conditions...;
在我的Java应用程序中,我想通过Hibernate的Foo
视图获取信息结果。所以我必须使用createSQLQuery()
方法:
public List<SomeObject> findSomeObjects() {
Query q = sessionFactory.getCurrentSession()
.createSQLQuery("select f.* from Foo f")
.addEntity(A.class).addEntity(B.class);
List l = q.list();
//here I want to get object of A class and B class from return l
//and prepare return list of SomeObject
}
SomeObject
聚集A和B类。
我从返回列表中获取A类和B类的对象的问题并构造SomeObject
列表。我怎样才能正确使用它?
修改
A
还有一列fk_c
,它是C
表的外键B
还有一列fk_d
,它是D
tabel的外键答案 0 :(得分:1)
创建一个域类,其中包含视图“Foo”中的所有字段,如下所示。
Class Foo {
private String a_id;
private String a1;
private String a2;
private String a3;
private String b_id;
private String b1;
private String b2;
private String b3;
// Getters
// Setters
}
修改您的SQL查询,如下所示:
public List<SomeObject> findSomeObjects() {
Query q = sessionFactory.getCurrentSession()
.createSQLQuery("select f.* from Foo f")
.setResultTransformer(Transformers.aliasToBean(Foo.class))
List l = q.list();
// here you can iterate through the list to fetch the fields and
// create a own custom object as per your requirement.
}
替代解决方案:
您还可以为视图“Foo”创建一个Entity类,并编写条件查询以获取结果。
请查看以下链接:
DB View to Hibernate Entity Mapping
How to map a view with Hibernate
修改强>
如果您的视图中有其他表(C,D)的外键,我建议您通过将关系添加到其他依赖实体(C,D)来将此视图映射为休眠实体类。
@Entity
@Immutable
Class Foo {
private String a_id;
private String a1;
private String a2;
private String a3;
private String b_id;
private String b1;
private String b2;
private String b3;
@OneToMany
@JoinColumn(name = "C_id")
private List<C> c;
@OneToMany
@JoinColumn(name = "d_id")
private List<D> d;
// Getters
// Setters
}