这里面的代码是用kotlin实现的, 不理解的可以跳过
首先事情发生是我想用注解自动建表结果无法识别@Coloum等注解, 我想用一个公共的父类来定义好固定的字段
@MappedSuperclass
abstract class BaseTable<ID>: Serializable {
protected abstract var id: ID
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) get
protected abstract var createTime: LocalDateTime
@CreationTimestamp
@Column(name = "create_time", nullable = false, updatable = false)
get
protected abstract var updateTime: LocalDateTime
@UpdateTimestamp
@Column(name = "update_time", nullable = false)
get
}
Code表代码
@Entity
@Table(name = "code", indexes = [Index(name = "uuid_index", columnList = "uuid", unique = true)])
class CodeTable(
id: Long,
@Column(name = "uuid", length = 32, nullable = false)
@ColumnDefault("''")
override var uuid: String = "",
@Column(name = "language", length = 20, nullable = false)
@ColumnDefault("'txt'")
override var language: String = "txt",
@Column(name = "content", columnDefinition = "text", nullable = false)
override var content: String,
@Version
@Column(name = "version", nullable = false)
override var version: Int = 0,
createTime: LocalDateTime = LocalDateTime.now(),
updateTime: LocalDateTime = LocalDateTime.now(),
) : BaseTable<Long>(id, createTime, updateTime), Code
这两个类看起来没有任何异常且非常正常, 但当我看到数据库的content字段是varchar(255)我就纳闷了,我配置的明明是@Column(... columnDefinition = "text")
而且其他的字段似乎都没有生效, 我都怀疑是kotlin编译有啥问题, 结果JPA的机制是方法注解和属性注解只会按照一种形式读取,我的父类是通过方法注解,而子类是通过属性注解, 结果JPA按照只读取了方法上的注解, 导致找不到无法正常建表, 经过一番修改后正常;
修改后
@MappedSuperclass
abstract class BaseTable<ID: Serializable> (
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected var id: ID,
@CreationTimestamp
@Column(name = "create_time", nullable = false, updatable = false)
protected var createTime: LocalDateTime,
@UpdateTimestamp
@Column(name = "update_time", nullable = false)
protected var updateTime: LocalDateTime,
) : Serializable
@Entity
@Table(name = "code", indexes = [Index(name = "uuid_index", columnList = "uuid", unique = true)])
class CodeTable(
id: Long,
@Column(name = "uuid", length = 32, nullable = false)
@ColumnDefault("''")
override var uuid: String = "",
@Column(name = "language", length = 20, nullable = false)
@ColumnDefault("'txt'")
override var language: String = "txt",
@Column(name = "content", columnDefinition = "text", nullable = false)
override var content: String,
@Version
@Column(name = "version", nullable = false)
override var version: Int = 0,
createTime: LocalDateTime = LocalDateTime.now(),
updateTime: LocalDateTime = LocalDateTime.now(),
) : BaseTable<Long>(id, createTime, updateTime), Code