Kotlin JPA实体ID [英] Kotlin JPA entity ID

查看:217
本文介绍了Kotlin JPA实体ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义JPA实体ID的"kotlin方法"是什么?

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

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

还是有更好的方法来避免可为空的id?

Or is there any better one to avoid nullable id?

推荐答案

您可以使用0值而不是空值.

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编译为Java,Java具有原始类型long和类Long

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

按照 Java 11.1.21 Id注释部分中的持久性规范 都可以用于Id:

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

应用了Id注释的字段或属性应该是一个 以下类型之一:任何 Java原始类型;任何原始包装器类型; java.lang.String; java.util.Date; java.sql.Date; java.math.BigDecimal; java.math.BigInteger [109].

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].

使用Class优于原始类型,因为null具有更明确的含义.但是从规范来看,两者都是可能的,并且您必须确定天气情况,而不是jpa风格还是相反,您更倾向于Kotlins nullsafety.

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.

这篇关于Kotlin JPA实体ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆