如何使用 Hibernate 将原始 sql 投影放入对象中?
假设我有一个以以下投影开头的查询:
SELECT t.term as term, count(g.id) as amount
这是原始 sql,我在 Hibernate 会话对象上使用 createSqlQuery。我想做的是将这些投影放入具有“term”和“amount”属性的对象中。
使用 HQL,我们可以使用“select new ClassName(...)”,但这不适用于原始 SQL 查询。
我们该怎么做呢?我拿回了一堆 [LObject's...但我不知道如何处理它们。如果我能让 Hibernate 将它们放入某种非实体值对象中,那就太好了。
谢谢!
Let's say I have a query that begins with the following projections:
SELECT t.term as term, count(g.id) as amount
This is raw sql, and I am using createSqlQuery on the Hibernate session object. What I'd like to do is take these projections and put them in an object that has a "term" and "amount" properties.
With HQL, we can use "select new ClassName(...)", but this doesn't work with a raw SQL query.
How do we do it? I get back a bunch of [LObject's... and I have no idea what to do with them. If I can get Hibernate to put them into some kind of non-entity value object, that'd be great.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过应用“结果转换器”来告诉 Hibernate 从本机 SQL 查询返回非托管值对象。来自参考文档:
You can tell Hibernate to return non-managed value objects from a native SQL query by applying a "result transformer". From the reference documentation:
检查 http://docs.jboss.org /hibernate/core/3.3/reference/en/html/querysql.html#d0e13696
假设您的对象具有 term 和 amount 属性,只有这 2 个对象属性,与您的原始查询类似SQL 应该返回这些对象的列表,然后您可以逐一迭代该列表。
Check http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#d0e13696
Assuming your object with the term and amount properties has only those 2 object attributes a similar query with your raw SQL should return a list of those objects which you can then iterate through one by one.