在equals和hashcode方法中使用Hibernate实体对象的自动生成的ID [英] Using auto generated id of Hibernate entity object in the equals and hashcode methods

查看:157
本文介绍了在equals和hashcode方法中使用Hibernate实体对象的自动生成的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可爱的等于和哈希码,所有的理论都在此处和也在此处

Lovely equals and hashcode, all the theory is here and also here

我决定在多个休眠实体/域对象的equals()和hashcode()中使用自动生成的ID.

I have taken the decision to use the auto-generated id within equals() and hashcode() in a number of my hibernate entity/domain objects.

但是,许多网站都说您不应该这样做,因为存在在比较对象或使用哈希码的过程中将对象第一次持久保存到数据库中的风险.

However, a number of websites say you should never do this due to the risk of persisting an object to the database for the first time whilst it is in the process of being compared or using hashcode.

我的观点是,在大多数用例中,这比其他任何要更改的字段都不太可能.

My point of view is that in most use cases this is much more unlikely than any other field being changed.

单个域对象在首次创建时具有一次生成的ID,而几乎每个其他字段都有机会在正常业务流程中进行更改(甚至可以更改唯一的用户名...).

The individual domain objects have the id generated once when they are first created, whereas nearly every other field has the opportunity to be altered during normal business processes (even a unique username can be changed ... ).

在我的许多域对象中,唯一ID几乎是唯一要考虑的合适字段(人,地址,宠物,...客户等)?组合字段是一个好主意,但是从不我认为使用自动生成的ID并不是很好的建议.

And in many of my domain objects the unique id is pretty much the only suitable field to be considered (Person, Address, Pet, ... Customer etc etc ? Combining fields is a good idea, but never using the auto generated id is, I think, not good advice.

我想念其他东西吗?

推荐答案

您应该阅读等于和HashCode 在Hibernate社区Wiki上.

You should read Equals and HashCode on the Hibernate Community Wiki.

equals中不使用数据库标识符的主要原因,并且暗示hashCode是用于处理已存储但未持久的实体.在持久化之前,除非您小心地明确处理该情况,否则所有实例都将是equal.

The main reason for not using the database identifier in equals, and by implication, hashCode is for dealing with stored, but not persisted, entities. Prior to persistence all you instances are going to be equal, unless you take care to handle that case explicitly.

如果您知道自己不会出现这种情况,并且确保已对其进行了充分的记录,则可能会很好.您以后随时可以更改实现.

If you know that you're not going to be in this scenario, and you make sure it's well documented, you may well be OK. You can always change the implementations later.

这篇关于在equals和hashcode方法中使用Hibernate实体对象的自动生成的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆