Kotlin JPA entity ID

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.

Tags:

Jpa

Kotlin