The java.util.Date
itself is a mutable object. As such even if Kotlin data class (with date field declared val) prevents me from changing the reference I can modify the date object itself to change its value.
Ways I could come up with:
Use normal class, override getter and setter. In each use the clone method to make a copy of given date.
@Column(name = "db_date")
private var dbDate: Date? = null
get() = dbDate?.clone() as Date
set(date) {
field = date?.clone() as Date
}
Also I can't use the copy
method of data class since these classes are hibernate entities. So I need to modify them via setters.
The reason I want to use data classes for my entities is because these implement equals
and hashcode
by default. We had been using lombok in java for this and now convincing team to create these methods is tough. Even if generation happens by IDE its still going to be checked into source control.
So is there any way I could do custom setters on data class logic. Or any way I can generate equals and hashcode for normal classes without checking them in source control?
Edit: In comments it was pointed out to use java.time.Instant
which is Immutable. The issue I am faced with is that this is a Hibernate Entity Class and we are using hibernate 3.6. Instant support came in hibernate 5.2 so we are way behind and migration of hibernate will be a heavy task. What I did notice is that kotlin data classes do allow setters and getters just in a different way. Code below:
@Entity
@Table(name = "my_table")
data class MyTable(
@Id
@Column(name = "id")
var id: Long? = null,
@Column(name = "my_date")
private var date: Date? = null,
) {
fun getDate():Date = gradedDate?.clone() as Date
fun setDate(date: Date?) {
this.date = date?.clone() as Date
}
}