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

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

问题描述

可爱的equals和hashcode,所有的理论都是 here 和也此处



我决定在一些hibernate实体/域对象中使用equals()和hashcode()中的自动生成的id。然而,许多网站表示,你永远不应该这样做,因为在第一次存在对象的过程中存在持久化对象到数据库的风险比较或使用散列码。



我的观点是,在大多数使用情况下,这比任何其他字段更改的可能性要小得多。



个别域对象的id在第一次创建时会生成一次,而几乎所有其他字段都有机会在正常业务流程期间进行更改(甚至可以更改唯一的用户名......)。



在我的许多域对象中,唯一的id几乎是唯一适合考虑的领域(Person,Address,Pet,... Customer等等)?合并字段是一个好主意,但永远使用自动生成的ID是,我认为,不是很好的建议。



我是否缺少别的东西?

解决方案

您应该阅读 Equals和HashCode



中不使用数据库标识符的主要原因等于

code>,并且通过暗示, hashCode 用于处理已存储但未持久的实体。在持久化之前,所有实例都将为等于,除非你明确地处理这种情况。



如果你知道你不会在这种情况下,并且你确定它有很好的文档记录,你可能没问题,你可以稍后改变实施。


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

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.

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 ... ).

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.

Am I missing something else ?

解决方案

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

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方法中使用自动生成的hibenate实体对象的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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