I understand from both personal experience and this discussion that when a data class inherits from another class that inherited class's fields are not included in the data class's copy function.
I'm interested in what the options are for getting around this issue.
Specifically, I have a JPA @MappedSuperClass for my JPA entities, which are data classes. In the super class I set up the entity ID, which (at least so far) I always want to do the same way. There are some other things I may want to do in it as well, like set up a created date, last updated date, etc.
Options I've considered so far:
Copy paste the ID, created date, etc. into every entity. Pros: it's easy and copy method works. Cons: Fails DRY and you can't handle all entities using a shared super class. (But could create an interface for that.)
Make override the super class's values and pass them to the super class.
You still need to copy paste the override values into every entity, but at least you don't have to copy the annotations.
@Entity
data class Comment(
@Lob
comment: String,
override val id: Long = -1
) : BaseEntity(id)
@MappedSuperclass
abstract class BaseEntity(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
open val id: Long = -1
)
- ??? I can't even think of a third option that works. Is there another way to do it? Make ID a var and create a custom copy method every time? That sounds ugly.