Jpa设置唯一索引

相对简单的设置唯一索引的方式如下:

1
2
@Column(unique=true)
String username;

另外还有一个@UniqueConstraint注解,是在table这个level下面的,一般用于建多个column的索引,参考如下:

1
2
3
4
@Entity
@Table(uniqueConstraints=arrayOf(UniqueConstraint(columnNames=arrayOf("book", "chapter_number"))))
class Chapter(@ManyToOne var book:Book,
@Column var chapterNumber:Int)

#特别注意

unique in @Column is used only if you let your JPA provider create the database for you - it will create the unique constraint on the specified column. But if you already have the database, or you alter it once created, then unique doesn’t have any effect.

也就是说,@Column(unique=true)只有在新建表的时候有作用,后期增加字段或者更新字段的时候,不起作用