简体   繁体   English

子类的Hibernate映射表

[英]Hibernate mapping table for subclass

I have 3 classes: 我有3节课:

Person {
    int id;
    String name;
    String lastName;
}

Employee extends Person {
    //some additional data
}

Owner extends Person {
    //some additional data
}

For each class I have separate table. 对于每个班级,我都有单独的表格。 In Employee table the key should be exactly the same as in Person table. Employee表中,键应与在Person表中的键完全相同。

And now when I insert Employee class there should be one record in Person table, one in Employee with the same ID (lets assume this is value 1). 现在,当我插入Employee类时,在Person表中应该有一条记录,在Employee有一条具有相同ID (让我们假定这是值1)。

After that I want to insert Owner class and I want it to be the same Person (ID=1) so after inserting Owner It should be added only one record in table Owner, but record in table Person should be left as it is. 之后,我想插入Owner类,并且希望它是同一个人(ID = 1),所以在插入Owner之后,应该只在表Owner中添加一条记录,但是应该保留表Person中的记录。

I have tried this: http://viralpatel.net/blogs/hibernate-inheritance-table-per-subclass-annotation-xml-mapping/ 我已经尝试过: http : //viralpatel.net/blogs/hibernate-inheritance-table-per-subclass-annotation-xml-mapping/

Inserting first class is OK, inserting second with diffrent ID is ok, getting objects from db is ok, but whet I want to add Owner class with the same ID such as the existing person I got hibernateException... Can anyone help me? 插入第一个类是可以的,插入具有不同ID的第二个是可以的,可以从db获取对象,但是我想添加具有相同ID的Owner类,例如我有hibernateException的现有人...有人可以帮我吗?

It's plain impossible. 根本不可能。 Since Java only has single inheritance, an object can't be both an employee and an owner. 由于Java仅具有单一继承,因此对象不能既是雇员又是所有者。 You shouldn't use inheritance to map these associations. 您不应该使用继承来映射这些关联。

Instead, you should have Person have a OnetoOne association with its Employee role, and a OnetoOne association to its Owner role. 相反,您应该使Person具有与其Employee角色的OnetoOne关联,以及与其Owner角色的OnetoOne关联。

"It's plain impossible." “这是绝对不可能的。” In my code example Employee extends Profile and Owner exstends Profile. 在我的代码示例中,员工扩展配置文件,而所有者扩展配置文件。

If I understend corectlly you anwser you suggest something like this: 如果我完全不理解您的建议,那么您会提出以下建议:

Person{
Employee emp;
Owner owner;
}

In my first class hierarhy I was able to do: 在我的头等课上,我能够做到:

Person getPersonFromDb( Class class, int id){  ...  session.get(class, id) ... }

Owner o = (Owner) getPersonFromDb(Owner.class, id);
Employee e =(Employee) getPersonFromDb(Employee.class, id);

In your approach I can't have something like this... 用你的方法我不能有这样的事情...

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

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