Unique Constraint Not Enforce on SchemaExport of Hibernate
I am quite unsure why my entity class does not create my required table schema
@Entity
@Table(name = "User")
public class User implements Serializable {
private Long id;
private String loginName;
@Id
@GeneratedValue
public Long getId() {
return id;
}
@Column(name = "login_name", unique = true)
public String getLoginName() {
return loginName;
}
//other setters
}
When I use the Schema export.
new SchemaExport(config).create(true, true);
It creates this 开发者_运维技巧SQL but then it does not add any unique constraints to my login_name field.
drop table User
create table User (id bigint generated by default as identity, login_name varchar(255)primary key (id))
I am using Apache Derby and I have checked the reference manual of Derby and it does support the Unique constraint on the column. I tried adding a uniqueconstraint annotation on the class but the result is the same.
Any idea?
The problem is that Derby extends a DB2 Dialect, which specifies that "supportsNotNullUnique" as "false". So, the solution is to either create your custom Derby dialect and changing this method to return "true", or to mark your field as nullable=false.
@Column(name = "login_name", unique = true, nullable=false)
or
import org.hibernate.dialect.DerbyDialect;
public class CustomDerbyDialect extends DerbyDialect {
public boolean supportsNotNullUnique() {
return true;
}
}
精彩评论