如何选择指定字段,并返回一个对象(由用户定义)列表 - (hibernate)
Hibernate api 文档引入了 Criteria 和 Projections 类,它们可以帮助选择表的指定字段并返回对象列表。
但是,我想获得一个 A 类的列表(A 是我自己定义的),因此我可以将它用作通常的对象列表。
例如,我有一个类:
class A {
String field1;
String field2;
String field3;
String getField1() {
return field1;
}
...
}
数据库中的表具有相同的字段。
我只想选择 field1
和 field2
。所以我尝试了:
List<A> list = (List<A>) ession.createCriteria(A.class)
.setProjection(Projections.projectionList()
.add(Projections.property("field1"))
.add(Projections.property("field1"))
.list();
这显然不正确:java.lang.ClassCastException
!
有什么办法可以得到A级的名单吗?我想直接使用A的方法,例如:
list.get(0).getField1()
thks.......
Hibernate api doc introduces the Criteria and Projections classes, which can help select specified fields of table and return an Object list.
BUT, i want to get an class A's list (A is defined by myself), thus i can use it as usual object list.
for example,i have a class:
class A {
String field1;
String field2;
String field3;
String getField1() {
return field1;
}
...
}
the table in database has the same fields.
I want to select field1
and field2
only. so I tried:
List<A> list = (List<A>) ession.createCriteria(A.class)
.setProjection(Projections.projectionList()
.add(Projections.property("field1"))
.add(Projections.property("field1"))
.list();
It is obviously not correct: java.lang.ClassCastException
!!
Is there any way to get a class A's list? i want to use A's method Directly, like:
list.get(0).getField1()
thks.......
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定 Hibernate Criteria API 是否允许投影到任意类的对象,但您可以通过“调用”HQL select 子句中的构造函数,将 HQL 查询结果投影到使用 HQL 查询构造的任意类的对象:
请参阅 select 子句 Hibernate 手册,章节 HQL:Hibernate 查询语言。
I am unsure if Hibernate Criteria API allows to project to objects of an arbitrary class but you can project the HQL query results to objects of an arbitrary class constructed withing HQL query by "calling" the constructor in the HQL select clause:
See The select clause in Hibernate manual, Chapter HQL: The Hibernate Query Language.
如果您在条件上设置投影,查询将不再返回实体列表,而是返回标量数组列表。这是一件好事,因为返回部分加载的实体会由于不变量被破坏而导致大量错误(非空字段为空、卸载关联等)。
因此,您应该使用另一种对象(值对象)来表示加载的字段:
Hibernate 也可以使用反射、使用
AliasToBeanResultTransformer
或AliasToBeanConstructorResultTransformer
为您完成此转换。代码>.If you set a projection on the criteria, the query won't return a list of entities anymore, but a list of arrays of scalars. This is a good thing, since returning a partially loaded entity would result in a multitude of bugs due to invariants being broken (non null fields being null, unloaded associations, etc.).
So, you should use another kind of object (a value object) to represent the loaded fields :
Hibernate can also do this transformation for you, using reflection, using an
AliasToBeanResultTransformer
or anAliasToBeanConstructorResultTransformer
.