开发者

Specifying non unique column as @Id field in hibernate

I am storing results of a @Nam开发者_如何学运维edNativeQuery 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 ?


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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜