有限制的 Hibernate 实体
我们有一个映射到休眠实体的数据库表。到目前为止一切都很顺利...
但是我们想要的是只映射满足特定标准的实体,例如“distinct(fieldA,fieldB)”...
是否可以使用 hibernate 和 hibernate 注释进行映射?我们怎样才能做到呢?用@Filter?
We have a DB table that is mapped into a hibernate entity. So far everything goes well...
However what we want is to only map enentitys that satisty a specific criteria, like ' distinct(fieldA,fieldB) '...
Is it possible to map with hibernate and hibernate annotations? How can we do it? With @Filter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议您使用
@Where
注解。此注释可用于集合的元素 Entity 或目标实体。您提供一个用 sql 编写的子句属性,该属性将应用于 hibernate 对该实体执行的任何选择。它非常易于使用且可读性强。这是一个例子。
I would recommend that you use
@Where
annotation. This annotation can be used on the element Entity or target entity of a collection. You provide a clause attribute written in sql that will be applied to any select that hibernate performs on that entity. It is very easy to use and very readable.Here is an example.
您可以创建一个视图,然后将该视图映射到实体:
一个选项是正常映射表,然后您可以通过查询或 过滤器。
您还可以进行本机 SQL 查询< /a> 并将实体映射到结果上:
也可以将 DISTINCT 添加到这种类型的HQL查询:
方法1、3、4将进行只读映射。
您能否更具体地说明您所使用的标准?视图方法更通用,因为您无法使用休眠查询或过滤器完成所有操作。
You could create a view and then map that view to entity:
One option is to map the table normally, then you could fetch your always entities through a query or a filter.
You could also make a native SQL query and map the entity on the results:
It might be also possible to add DISTINCT to this type of HQL query:
Methods 1, 3 and 4 will make a read-only mapping.
Could you be more specific about the criteria you are using? The view approach is more generic since you can't do everything with a hibernate query or filter.
也许您可以创建一个新的 Pojo 来封装字段以及它们应该统计的条件。然后将该类设置为“自定义用户定义类型”,这样 Hibernate 将必须使用您提供的映射类来映射该“类型”。
perhaps you could create a new Pojo that encapsulates the fields and the condition that they should statisy . And then then make that class a 'custom user defined type', such that Hibernate will have to use the mapping class that you provide, for mapping that 'type'..
除了 Juha 提到的选项之外,您还可以使用 NamedNativeQuery 和 SqlResultSetMapping 注释直接从 SQL 查询创建对象。
根据您的喜好调整 SQL 查询
In addition to the options mentioned by Juha, you can also create an object directly out of a SQL query using the NamedNativeQuery and SqlResultSetMapping annotations.
Flavor the SQL query to your taste