Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin JPA entity ID

Tags:

jpa

kotlin

What is "the kotlin way" to define JPA entity ID?

@Entity
data class User (
        @Id @GeneratedValue
        var id: Long? = null,
        ...
)

Or is there any better one to avoid nullable id?

like image 334
Ondřej Míchal Avatar asked Apr 10 '18 07:04

Ondřej Míchal


1 Answers

You can use a 0 value rather than a null value.

@Entity
data class User (
        @Id @GeneratedValue
        var id: Long = 0,
        ...
)

Autogeneration should still find the next sequence.

Kotlin compiles to Java, which has both, a primitive type long and a Class Long

As per the Java Persistence Specification in section 11.1.21 Id Annotation both can be used for the Id:

The field or property to which the Id annotation is applied should be one of the following types: any Java primitive type; any primitive wrapper type; java.lang.String; java.util.Date; java.sql.Date; java.math.BigDecimal; java.math.BigInteger[109].

There is an advantage in using the Class over the primitive, as null has a more unambiguous meaning. But from the spec both are possible and you have to decide weather you favor Kotlins nullsafety over the the jpa style or the other way around.

like image 105
phisch Avatar answered Sep 27 '22 23:09

phisch