@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"username"})})
public class SomeEntity {
@Column(name = "username")
public String username;
}
@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames = {"id_1" , "id_2"})})
public class class_name {
@Id
@GeneratedValue
public Long id;
@NotNull
public Long id_1;
@NotNull
public Long id_2;
}
@Entity
@Table(uniqueConstraints=arrayOf(UniqueConstraint(columnNames=arrayOf("book", "chapter_number"))))
class Chapter(@ManyToOne var book:Book,
@Column var chapterNumber:Int)
从Kotlin 1.2开始,可以使用[...]语法,因此代码变得更加简单
@Entity
@Table(uniqueConstraints=[UniqueConstraint(columnNames=["book", "chapter_number"])])
class Chapter(@ManyToOne var book:Book,
@Column var chapterNumber:Int)
唯一注释应该放在属性声明的正上方。
UniqueContraints进入数据类声明上面的@Table注释。见下文:< / p >
@Entity
@Table(uniqueConstraints= arrayOf(UniqueConstraint(columnNames = arrayOf("col_1", "col_2"))))
data class Action(
@Id @GeneratedValue @Column(unique = true)
val id: Long?,
val col_1: Long?,
val col_2: Long?,
)
在某些情况下(当使用MySql时),我们必须通过添加@Column(name="product_id", length = 6)来提供唯一约束中使用的列的长度,因为默认情况下Hibernate将创建具有最大大小的列(默认行为),这在MySql中创建唯一约束(Specified key was too long; max key length is 1000 bytes)时会生成一个错误