使用UUID作为业务键和equals / hash方法 [英] Using UUID as business key and equals/hashmethod

查看:147
本文介绍了使用UUID作为业务键和equals / hash方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个新的应用程序,我需要一些关于如何实现equals方法和hashCode方法的帮助。我一直在阅读这里已经提到过的很多问题,我也读了几篇博文,引导我提出这个问题。

I am working on a new application and I need some help on how to implement the equals method and the hashCode method. I have been reading many questions already asked here on SO, and I have also read several blog posts that has lead me to this question.

首先是一些技术信息:我我正在使用JPA(EclipseLink),而应用程序是用于Java EE。

A little technical information first: I am using JPA (EclipseLink) and the application is for Java EE.

在我读过之后你应该使用hashCode和equals的不可变值,但是因为class通常是可修改的,你不能使用它们。你也不能使用主键(JPA),因为在你坚持它之前你没有主键。所以我在想的是使用UUID。对于equals和hashCode都有,但我之前从未这样做过,所以我想知道是否有人认为这很糟糕(为什么?)和可能的缺点(除了获得相同ID的微小机会)?使用UUID并在构造函数中将其设置为将从一开始就为所有对象提供业务ID。并且我将它变为不可变并将其保存到数据库中。

After what I have read you should use immutable values for hashCode and equals, but since the fields in the class is usually modifiable you can't use them. Nor can you use the primary key (JPA) because you won't have one before you have persisted it. So what I am thinking about is to use UUID. Both for equals and hashCode, but I have never done that before so I wonder if somebody thinks this is bad (why?) and possible downsides (apart from the tiny tiny tiny chance of getting the same ID)? Using a UUID and asign it in the constructor will give all objects a business ID from the very start. And I will make it immutable and save it to the database.

这种方法是不是很糟糕?

Is this approach bad?

推荐答案

IMO UUID工作得很好,我建议这样做。

IMO the UUID will work just fine and i would recommend doing so.

我不能发现这种方法的任何缺点,因为这种可能性击中2个相同的值是无限小的。

I can't find any drawbacks to this approach since the possibility of hitting 2 same values is infinitely small.

这篇关于使用UUID作为业务键和equals / hash方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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