I have a Java bean. Now, I want to be sure that the field should be unique.
I am using the following code:
@UniqueConstraint(columnNames={\"username\
Unique annotation should be placed right above the attribute declaration. UniqueContraints go into the @Table annotation above the data class declaration. See below:
@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?,
)
Note: In Kotlin the syntax for declaring the arrays in annotations uses arrayOf(...)
instead of {...}
@Entity
@Table(uniqueConstraints=arrayOf(UniqueConstraint(columnNames=arrayOf("book", "chapter_number"))))
class Chapter(@ManyToOne var book:Book,
@Column var chapterNumber:Int)
Note: As of Kotlin 1.2 its is possible to use the [...]
syntax so the code become much simpler
@Entity
@Table(uniqueConstraints=[UniqueConstraint(columnNames=["book", "chapter_number"])])
class Chapter(@ManyToOne var book:Book,
@Column var chapterNumber:Int)