We have plenty of java applications and are trying to implement our first one in Kotlin. The Question is: what is the best way to initialize the properties of a simple hibernate model?
Let's take the following example in Java:
@Entity
@Table(name = "Session_Ids")
public class SessionId() {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
@Column
protected Long number;
}
Now let's assume that the id and the number in the database can never be null. So after hibernate is done with everything the model will always have a value in the id field and a value in the number field.
How can I do that in Kotlin? I can't initialize them with null because I have to declare those fields as Nullable which they shouldn't be. I can not use lateinit because both fields are primitive long types.
The only way I see to prevent defining them as nullable is to initialize them with some wrong default value. Something like
var number: Long = -1
But that looks wrong to me.
Is there some kind of best practice to do something like this in Kotlin?
Thank you in advance!
Another solution I found are kotlins data classes but I'm still not sure if this is a good way.
The Kotlin version of the Java class in my question would look like this:
@Entity
@Table(name = "Session_Ids")
data class SessionId(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long?,
@Column
var number: Long,
){
constructor(userId: Long): this(null, userId)
}
The id still is nullable because otherwise hibernate may have conflicts with existing entities with the same IDs. The only other option would be 0 as a value but I think for an unpersisted entity null is more expactable than 0.
I added the secondary constructor to prevent passing null for the ID.
What do you think about that?