【问题标题】:fail to create unique constraint with hibernate annotation in a postgres database无法在 postgres 数据库中使用休眠注释创建唯一约束
【发布时间】:2012-01-08 09:12:42
【问题描述】:

我正在使用 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>

【问题讨论】:

  • 你是如何确定约束被忽略的?
  • 约束没有传递给数据库。另外,我对其进行了测试,它让我创建了重复的用户名

标签: hibernate postgresql annotations unique-constraint


【解决方案1】:

只需将属性“hbm2ddl.auto”设置为“create”,hibernate 就会重新创建具有唯一列的表。

【讨论】:

    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多