可以使用Kotlin数据类equals()方法而无需与JPA一起进一步修改? [英] Can a Kotlin data class equals() method be used without further modification in conjunction with JPA?

查看:734
本文介绍了可以使用Kotlin数据类equals()方法而无需与JPA一起进一步修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin 有一个Data类,它包含 toString(),equals(), hashCode()和copy()



可以 equals()和hashCode()



我们可以简单地依靠Kotlin的 equals()和hashcode()实现在我看来,除非你真正理解你在做什么,否则不应该使用Kotlin中的数据类。

对可变数据重写等于 / hashCode 可能会导致问题。
考虑你已经将一个可变类的实例添加到 HashSet 中,然后改变了该实例的某些属性。
这会影响由 hashCode 返回的值。



反过来,这使得 HashSet 来查找实例,因为它会在完全不同的散列表条目中查找它。
您将无法从 HashSet



中删除此实例。在kotlin中的数据类是:复数,恒定大小的向量。
不好的例子是:JPA实体,DTOs。



至于JPA,这些文章都是有见地的。
还有一种观点:您不应该为JPA实体覆盖 equals hashCode



理由:JPA提供者(Hibernate,EclipseLink)必须保证 a === b iff a和b在表中具有相同的主键,并且a和b都处于持久状态。
此分包合同可能会因分离的实体而中断。
但是,在我看来,与分离实体合作是一种应该避免的不好的做法。
这个唯一可能有意义的事情是将分离的实体存储在另一个JPA事务中。


Kotlin has a Data class that comes with toString(), equals(), hashCode(), and copy().

Can equals() and hashCode() be used "Straight out of the box" without further tuning for JPA classes? We usually have to spend a lot of time reading up on "Natural Keys", the persistence context lifecycle, etc. in articles linked below before feeling confident that we are doing the right thing:

Can we simply rely on Kotlin's equals() and hashcode() implementations now?

解决方案

In my opinion, data classes in Kotlin should not be used unless you really understand what you are doing.

Overriding equals/hashCode on mutable data can cause a problem. Consider you have added instance of a mutable class to HashSet, then changed some if properties of that instance. This affects value returned by hashCode.

In turn, this makes it impossible for HashSet to find the instance, since it will look for it in completely different hashtable entry. You won't be able to remove this instance from HashSet!

Good examples of candidates to be data classes in kotlin are: complex numbers, constant-sized vectors. Bad examples are: JPA entities, DTOs.

As for JPA, these articles are opinionated. There's another opinion: you should not override equals and hashCode for JPA entities at all.

Rationale: JPA providers (Hibernate, EclipseLink) must guarantee that a === b iff a and b have the same primary key in table, and both a and b are in persistent state. This contract may be broken for detached entities. But, in my opinion working with detached entities is a bad practice that one should avoid. This only thing that may have sence is to store detached entities to merge them in another JPA transaction.

这篇关于可以使用Kotlin数据类equals()方法而无需与JPA一起进一步修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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