Extending the Kotlin Data Class for use with JPA?

2019-08-23 11:00发布

问题:

Kotlin has a Data class that automatically implements equals and hashcode, but these are still not automatically usable in a JPA context.

In order to remedy this I was wondering what it would take to extend the Data type in order to either assign a "Business Key" or an id property that is final and non updatable and is initialized with a UUID that serves as the business key, and have equals() and hashcode() methods use that property for their implementation.

I was thinking roughly something like this:

jpa class User(id: JpaId, val name: String, val age: Int)

jpa class User(bid: JpaBid, val name: String, val age: Int)

Instead of using a Data class like this:

data class User(bid: long, val name: String, val age: Int)

We are using a new type of class jpa. We also have two new types, JpaId and JpaBid that are used to determine whether the id property should be a UUID or a business key, like an ISBN number, sku, etc.

If a JpaId type is used then the key is automatically generated. If a JpaBid is used then the key should be supplied in the constructor. This would ensure that as soon as a JPA entity is constructed, it can be uniquely identified. Thoughts? Is this something that is very straight forward to do in Kotlin, or do we need to get up in the JVM grill (Brand new to Kotlin)?