如何解决休眠:将@UniqueConstraint映射到子类的超类
Java EE 7, 休眠5.4.21.Final
为什么SubClass
继承了SuperClass
@UniqueConstraint
注释,或更具体地说,为什么Hibernate在SuperClass
表映射期间使用SubClass
注释?
如何在子类中覆盖@UniqueConstraint
?
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table( name = "supTable",uniqueConstraints = {
@UniqueConstraint( name = "UK_multi_col",columnNames = {"colOne","colTwo"})
}
)
public class SuperClass implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "id",unique = true,nullable = false)
protected Long id;
@Column(name = "colOne")
protected Long colOne;
@Column(name = "colTwo")
protected Long colTwo;
...
}
在"UK_multi_col"
中使用相同的名称@UniqueConstraint
不会在SubClass
中覆盖,并且会在SubClass
表中生成两个UNIQUE KEY。一个唯一的密钥来自SuperClass
,一个唯一的密钥来自SubClass
,其中应该只有一个(不包括主密钥)。
@Entity
@Table( name = "subTable","colTwo","colThree"})
}
)
public class SubClass extends SuperClass {
@Column(name = "colThree")
protected Long colThree;
...
}
create table test_subTable (
id bigint not null,colOne bigint,colTwo bigint,colThree bigint,primary key (id)
) engine=InnoDB
create table test_supTable (
id bigint not null,primary key (id)
) engine=InnoDB
alter table test_subTable
drop index UK_multi_col
alter table test_subTable
add constraint UK_multi_col unique (colOne,colTwo,colThree)
接下来的四行是在SuperClass
映射期间由SubClass
注释生成的代码:
alter table test_subTable
drop index UK_a5tjgjgpmww7otw30iyvmym1m
alter table test_subTable
add constraint UK_a5tjgjgpmww7otw30iyvmym1m unique (colOne,colTwo)
alter table test_supTable
drop index UK_multi_col
alter table test_supTable
add constraint UK_multi_col unique (colOne,colTwo)
数据库表:
| test_subtable | CREATE TABLE `test_subtable` (
`id` bigint(20) NOT NULL,`colOne` bigint(20) DEFAULT NULL,`colTwo` bigint(20) DEFAULT NULL,`colThree` bigint(20) DEFAULT NULL,PRIMARY KEY (`id`),UNIQUE KEY `UK_multi_col` (`colOne`,`colTwo`,`colThree`),UNIQUE KEY `UK_a5tjgjgpmww7otw30iyvmym1m` (`colOne`,`colTwo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
| test_suptable | CREATE TABLE `test_suptable` (
`id` bigint(20) NOT NULL,`colTwo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
有人能解决这个问题吗?
解决方法
经过一天的搜索和测试,看起来它像是一个Hibernate错误,使用EclipseLink进行测试会生成正确的数据库映射。我已经提交了要休眠的错误报告
有关测试用例,EclipseLink项目文件和发布状态,请参见:HHH-14234。
如果有人找到了解决该问题的好方法,请发布。
更新: 看起来该错误已得到修复,请参见: https://github.com/hibernate/hibernate-orm/pull/3574
更新: 此问题将在Hibernate 5.5.0版中修复
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。