是否应该在equals和hashCode中考虑JPA实体的id字段? [英] Should the id field of a JPA entity be considered in equals and hashCode?

查看:252
本文介绍了是否应该在equals和hashCode中考虑JPA实体的id字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用JPA2和EclipseLink为数据库应用程序编写测试时遇到了问题:

I hit a problem when writing tests for a database application using JPA2 and EclipseLink:

我将一些实体添加到数据库中,稍后检索它并想要比较它到一个具有我期望的值的实例,我希望确认这个加法符合我的意图。

I add some entity to a database, retrieve it later and want to compare it to an instance which has the values I expect to confirm that the addition worked as I intended.

首先我写了类似

assertEquals(expResult, dbResult);

失败了,因为我真的不知道 id <的值/ code>字段,由数据库生成,因此 dbResult 与我创建的 expResult 不同 new 并手动填充。

which failed, because I can't really know the value of id field, which is generated by the database and therefore dbResult differs from expResult which I created with new and populated manually.

我看到两个选项:


  • 我从等于和<$中删除 id 字段c $ c> hashCode 以便比较仅基于实际值。我不知道这是否会导致数据库或其他地方出现问题。

  • Either I remove the id field from equals and hashCode so that the comparison is only based on the "real values". I don't know if this causes problems in the database or elsewhere, though.

或者我编写测试以明确检查除$ id 手动。

Or I write my tests to explicitly check every field except id manually.

我该怎么办?

推荐答案

你可能会发现很多关于这个问题的争议。我的立场是,绝对不要将数据库主键用于应用程序中的任何内容。它应该是完全不可见的。通过其他属性或属性组合识别应用程序中的对象。

You might find a lot of controversy about this one. My stance is that you absolutely don't use a database primary key for anything in your application. It should be completely invisible. Identify your objects in your application by some other property or combination of properties.

在测试持久性操作前面,您真正想要的是检查字段保存并正确加载,也许主键在保存时分配了一些值。这根本不是equals方法的工作。

On the "testing persistence operations" front, what you really want is probably to check that the fields were saved and loaded correctly and maybe that the primary key got assigned some value when you saved it. This probably isn't a job for the equals method at all.

这篇关于是否应该在equals和hashCode中考虑JPA实体的id字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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