我正在尝试评估此Hibernate文档中的映射: 第2.2.3.1节。生成标识符属性
在文档中,Person和MedicalHistory有@OneToOne映射(MedicalHistory指向Person),文档提出了两种映射策略:
第一个策略:
@Entity
class MedicalHistory implements Serializable {
@Id @OneToOne
@JoinColumn(name = "person_id")
Person patient;
}
@Entity
public class Person implements Serializable {
@Id @GeneratedValue Integer id;
}
第二战略:
@Entity
class MedicalHistory implements Serializable {
@Id Integer id;
@MapsId @OneToOne
@JoinColumn(name = "patient_id")
Person patient;
}
@Entity
class Person {
@Id @GeneratedValue Integer id;
}
现在一切正常,但是......
为了使事情变得更复杂,我添加了与MedicalHistory有@ManyToOne关系的另一个(第3个)表(类)。并且第一个策略将失败(而第二个策略仍然有效)。
我创建了另一个(第三个)类,命名为MedicalLog,它与MedicalHistory有@ManyToOne关系:
@Entity
public class MedicalLog implements Serializable
{
@Id @GeneratedValue
private int id;
@ManyToOne
@JoinColumn(name="MedicalHistory_id")
private MedicalHistory medicalHistory;
private String action;
private Timestamp time;
public MedicalLog(MedicalHistory mh , String action)
{
this.medicalHistory = mh;
this.action = action;
}
// other methods
}
当hibernate初始化时出现异常......:
Caused by: org.hibernate.AnnotationException: A Foreign key refering destiny.play.MedicalHistory from destiny.play.MedicalLog has the wrong number of column. should be 0
at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:421)
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:111)
就个人而言,我更喜欢策略1,因为它不会引入另一个整数id 变量。我觉得Object id(策略2)更舒服(OO风格)。
无论如何,虽然策略2有效,但我想知道有没有办法让策略1也有效?
非常感谢!
- 更新:表格创建 -
表创建(MySQL):
CREATE TABLE IF NOT EXISTS `Person` (
`id` int(10) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `MedicalHistory` (
`patient_id` int(10) NOT NULL,
PRIMARY KEY (`patient_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `MedicalLog` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`MedicalHistory_id` int(10) NOT NULL,
`action` varchar(15) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
希望有所帮助
答案 0 :(得分:1)
当hibernate初始化时发生异常......
您使用的是什么版本的Hibernate EntityManager?我无法在我的宠物项目中使用3.5.5-Final和相同的带注释的对象模型(第一个策略)重现该问题。
创建以下表格:
create table MedicalHistory (person_id integer not null, primary key (person_id), unique (person_id))
create table MedicalLog (id integer generated by default as identity, action varchar(255), time timestamp, MedicalHistory_id integer, primary key (id))
create table Person (id integer generated by default as identity, dept varchar(255), firstName varchar(255), gender varchar(255), lastName varchar(255), primary key (id))
alter table MedicalHistory add constraint FK306558E319ACB65E foreign key (person_id) references Person
alter table MedicalLog add constraint FKEDF39713FC40377E foreign key (MedicalHistory_id) references MedicalHistory
Hibernate初始化没有抱怨。