无法在 postgres 数据库中使用 hibernate 注释创建唯一约束
我使用hibernate,postgres 9.1,并且我尝试通过hibernate注释添加唯一约束(不在数据库中显式添加)
但是,db忽略唯一注释并且不创建约束。我还尝试在 @Table 注释中添加约束,但也失败了
@Entity
public class Person implements Serializable {
@Id
@Column(insertable=false, updatable=false)
@Type(type="java.lang.Long")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="PERSON_SEQ")
@SequenceGenerator(name="PERSON_SEQ", sequenceName="PERSON_SEQ", allocationSize=1)
private Long id;
@Column(unique=true)
private String username;
}
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Test1</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">postgres</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
Im using hibernate, postgres 9.1, and i'm trying to add a unique constraint via hibernate annotation (not adding explicitly in the database)
However, db ignores the unique annotation and doesn't create the constraint. I also tried add the contraint in the @Table annotation but failed too
@Entity
public class Person implements Serializable {
@Id
@Column(insertable=false, updatable=false)
@Type(type="java.lang.Long")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="PERSON_SEQ")
@SequenceGenerator(name="PERSON_SEQ", sequenceName="PERSON_SEQ", allocationSize=1)
private Long id;
@Column(unique=true)
private String username;
}
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Test1</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">postgres</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需将属性“hbm2ddl.auto”设置为“create”,hibernate 将重新创建具有唯一列的表。
Just set property "hbm2ddl.auto" to "create" and hibernate will recreate table with unique column.