可以使用Kotlin数据类equals()方法而无需与JPA一起进一步修改? [英] Can a Kotlin data class equals() method be used without further modification in conjunction with JPA?
问题描述
Kotlin 有一个Data类,它包含 toString(),equals(), hashCode()和copy()
。
可以 我们可以简单地依靠Kotlin的 equals()和hashCode()$ c $在没有进一步调整JPA类的情况下,可以使用直接开箱即用吗?我们通常不得不花很多时间阅读下面链接的文章中的Natural Keys,持久性上下文生命周期等,然后再确信我们做的是正确的事情:
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屋!