在hibernate中指定非唯一列作为@Id字段
我将 @NamedNativeQuery 的结果存储在 Bean 中,并且更常见的是查询结果不是唯一的,我也没有覆盖 bean 的 HashCode 和 Equals,因为我的目标只是填充数据(查询结果集),而不管它是重复或不重复。
我只是想知道在非唯一字段上指定 @Id 可能会产生什么影响?
I am storing results of a @NamedNativeQuery in a Bean , and more often the query results are not unique, nor I have overrided HashCode and Equals of the bean, as my objective is just to populate the data (query resultSet) irrespective of that is duplicate or not.
I just want to know what could be the repercussions of specifying the @Id on a non unique field ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
任何定义(从 RDBMS 到 Hibernate)的 ID 都是唯一的。它是识别和区分具体实体的唯一钥匙。以任何其他方式来做这件事都是一个可怕的反模式,你在任何情况下都不应该考虑它。
如果您需要聚合(“无论是否重复”),请使用聚合。选择不同的、和/或限制、和/或组。
它不抛出异常这一事实并不让它变得明智。将来它会咬你。我认为这会导致类似的情况:每当您通过 ID 加载实体时,它都会返回一个随机副本。即使您加载它们的集合,您也会获得随机副本。每当您更新时,它都会更新该随机副本。这是一个明智的实体身份吗? - 这就是 ID 的目的!
ID by any definition (from RDBMS through Hibernate) is unique. It is a unique key to identify and distinguish a concrete entity. Doing it in any other way is an awful antipattern and you should never, ever, under any circumstances even consider it.
If you need an aggregate ("irrespective of that is duplicate or not"), use an aggregate. Select with distinct, and/or limit, and/or group.
The fact that it doesn't throw an exception doesn't make it sensible. It is going to bite you in future. Offhand I think it would lead to something like: Whenever you load an entity by ID, it returns a random copy. Even if you load a collection of them, you get random copies. Whenever you update, it updates that random copy. How is that a sensible entity identity? - And that's the very purpose of the ID!
不可能。 ID 必须是唯一的。对于您的情况,您需要一个不是实体的 pojo,并通过 xml 映射值(也许也可以使用注释)。检查有关朴素查询的文档
Not possible. IDs have to be unique. For your case you need a pojo that is not an entity, and map the values via xml (perhaps possible with annotations as well). Check the docs about nayive queries