1

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>

2
  • How did you determine that constraint is ignored? Commented Jan 8, 2012 at 9:25
  • the constraint is not passed to the db. Also, i test it and it let me create duplicate usernames Commented Jan 8, 2012 at 9:29

1 Answer 1

1

Just set property "hbm2ddl.auto" to "create" and hibernate will recreate table with unique column.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.