使用Hibernate自动建表,User实体中的username字段希望给个唯一约束,但是自动建表却一直没有unique约束
@Entity @Table(name = "user") public class User { private int id; private String username; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(unique = true, nullable = false) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
键表的结果是索引中并没有唯一索引,多番尝试解决如下
@Entity @Table(name = "user") public class User { private int id; private String username; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(unique = true, length = 20, nullable = false) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
原因是我未指定 username 字段的长度,然后自动建表的字段长度是255字符,于是没有唯一索引,将长度指定为 20 ,删除表,重新执行建表便有了唯一索引。另需注意的是 nullable = false 。