通过投影查询返回实体
是否可以使用投影查询返回实体?
我已经使用 SQL 查询成功完成了此操作(见下文),但找不到如何使用投影查询来完成此操作。
Dim sql As String = "SELECT {a.*}, {b.*} FROM a LEFT OUTER JOIN b ON a.pk = b.fk")
' Convert SQL results into entities {a} and {b}
Dim query As IQuery = session.CreateSQLQuery(sql) _
.AddEntity("a", GetType(a)) _
.AddEntity("b", GetType(b))
Return query.List()
Is it possible to return an entity using a projection query?
I've successfully done it with a SQL query (see below), but can't find how to do it with a projection query.
Dim sql As String = "SELECT {a.*}, {b.*} FROM a LEFT OUTER JOIN b ON a.pk = b.fk")
' Convert SQL results into entities {a} and {b}
Dim query As IQuery = session.CreateSQLQuery(sql) _
.AddEntity("a", GetType(a)) _
.AddEntity("b", GetType(b))
Return query.List()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以从投影查询返回实体。
如果您使用 HQL 查询,则可以在 HQL select 子句中为给定类指定构造函数:
此示例要求 Foo 类具有适合 HQL 查询中使用的签名的构造函数。即:
您还可以使用 AliasToBean ResultTransformer,它自动将从查询返回的值映射到给定类型的属性。此方法要求查询中使用的别名直接映射到给定类型的属性。例如:
为了使这些示例正常工作,Foo 类可能如下所示:
上面的类包含第一个 HQL 示例的有效构造函数。它还定义了与第二个 HQL 查询中使用的别名一致的公共属性,这使得 AliasToBean 转换器可以从查询结果中填充 Foo 类型的实体。
但是,从您给出的示例来看,您似乎想从同一投影查询返回两种类型的实体。使用这些方法可能更难实现这一点。我做了一些快速测试,但没有任何运气。
更新:
您可以将 AliasToBean 结果转换器与 Criteria API 以及 HQL 结合使用。转换器的使用方式相同,但使用 Criteria 的投影查询看起来有点不同。以下是使用条件查询的示例:
Yes, you can return entities from projection queries.
If you are using a HQL query you can specify a constructor for the given class in the HQL select clause:
This example requires that the Foo class has a constructor that fits the signature used in the HQL query. I.e:
You could also use the AliasToBean ResultTransformer, which automatically maps the values returned from the query to the properties of a given type. This approach requires that the aliases used in the query map directly to properties of the given type. For example:
To make these examples work, the Foo class could look like this:
The class above contains a valid constructor for the first HQL example. It also defines public properties that align with the aliases used in the second HQL query, which makes it possible for the AliasToBean transformer to fill entities of the type Foo from the results of the query.
However, from the example that you give, it seems as if you want to return two types of entities from the same projection query. That might be harder to achieve using these methods. I did a couple of quick tests, without any luck.
Update:
You can use the AliasToBean result transformer with the Criteria API as well as with HQL. The transformer is used in the same way, but the projection query looks a bit different using Criteria. Here is an example that uses a criteria query: