Hibernate:如何从多个类的查询中获取结果
如果我的查询包含一个类,例如:
query = session.createQuery("select u from User as u");
queryResult = query.list();
然后我迭代它,其中 queryResult
是 User
类的对象。
那么如何从包含多个类的查询中获取结果呢?例如:
select u, g from User as u, Group as g where u.groupId = g.groupId and g.groupId = 1
If my query contains one class, like:
query = session.createQuery("select u from User as u");
queryResult = query.list();
then I iterate it, where queryResult
is an object of User
class.
So how to get result from query which contains more than one class? For example:
select u, g from User as u, Group as g where u.groupId = g.groupId and g.groupId = 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我相信你可以使用元组来做到这一点,但更重要的是,如果你的组和用户是相关的,就像该查询似乎建议用户应该有一个组字段(不要在你的用户类中使用groupId,hibernate应该为你解决这个问题)。如果是这种情况,您可以简单地使用
select u from User u join fetch u.group g where g.groupId = :id
进行查询(然后使用query.setParameter(1, 该查询中的 fetch 关键字使其成为急切加载,因此两个对象都将返回到 hibernate ,
hibernate 将使用 user.id 访问 Group 对象。 getGroup()。
You can do that using Tuples I believe, but more importantly, if your Group and User is related like that query seems to suggest User should have a Group field (don't use groupId in your User class, hibernate should sort this out for you). If that's the case you can simply query it using
select u from User u join fetch u.group g where g.groupId = :id
(then set the id usingquery.setParameter(1, id);
.The
fetch
keyword in that query makes it an eager load so both objects will be returned to hibernate which will return the User object to you. Access the Group object using user.getGroup().当您选择单个实体时,
query.list()
将返回包含您的实体的Object
的List
。当您选择多个实体时,
query.list()
将返回Object[]
的List
。数组的每个元素代表一个单独的实体。在这里阅读更多内容: http:// docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-select
When you select a single entity,
query.list()
will return aList
ofObject
containing your entities.When you select multiple entities,
query.list()
will return aList
ofObject[]
. Each element of the array represents a separate entity.Read more here: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-select
您还可以创建一个构造函数并返回一个对象:
假设类 Family 有一个适当的构造函数 - 作为实际类型安全的 Java 对象:
或一个列表:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-select
Also you can create a constructor and return a object:
Assuming that the class Family has an appropriate constructor - as an actual typesafe Java object:
Or a list:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-select
如果将 query.list() 转换为 Object[] 不起作用。您可以先将其转换为对象,然后将该对象转换为 Object[],如下所示
If casting the query.list() to Object[] does not work. You can first cast it to an Object and then cast that Object to Object[] like this