简体   繁体   English

唯一约束未对Hibernate的SchemaExport强制执行

[英]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. 它创建了此SQL,但随后没有向我的login_name字段添加任何唯一约束。

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. 我正在使用Apache Derby,并且已经检查了Derby的参考手册,它确实支持该列上的Unique约束。 I tried adding a uniqueconstraint annotation on the class but the result is the same. 我尝试在类上添加一个uniqueconstraint批注,但结果是相同的。

Any idea? 任何想法?

The problem is that Derby extends a DB2 Dialect, which specifies that "supportsNotNullUnique" as "false". 问题是Derby扩展了DB2语言,该语言将“ supportsNotNullUnique”指定为“ 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. 因此,解决方案是创建您的自定义Derby方言并更改此方法以返回“ true”,或将字段标记为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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM