无法在postgres数据库中使用hibernate注释创建唯一约束

时间:2012-01-08 09:12:42

标签: hibernate postgresql annotations unique-constraint

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

1 个答案:

答案 0 :(得分:1)

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