Hibernate 4: One class mapping Two tables - How to persist one object on both tables?

半城伤御伤魂 提交于 2019-12-05 16:49:59

I would strongly recommend to NOT to do that. It is very confusing. And not only for Hibernate but later it could bring more problems to you (other developer). To make it more clear, please, let's try to think about that issue in the POJO entities (not dynamic model)

Person person = new Person();
// fill properties
session.save(person); // as a person
session.save(person); // as a person audit 

Session will call insert only once, because there is only one instance. One object with one unique identifier. It cannot be evaluated as anything else then a person.

And the same is happening with your dynamic model. Try to observe your HashMap person after insertion. There should be a key "$type$" which should tell you how is that instance evaluated (as a person). It cannot act as anything else.

Suggested solution:

If you need to save one set information into two tables do it with more orientation to ORM style. E.g. clone the person into new HashMap() and save two independent entities

In your second mapping change this

<id name="idAudit" type="int">

to

<id name="id" type="int">
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!