Hibernate 4: One class mapping Two tables - How to

2019-05-10 00:25发布

I have this class Person mapping two tables: Persons and PersonsAUD (audit):

 <class catalog="test" name="test.Person" table="Persons" entity-name="Person">
    <id name="id" type="int">
      <column name="Id"/>
      <generator class="increment"/>
    </id>
    <property name="name" type="string">
      <column length="30" name="Name" not-null="true"/>
    </property>
    ...    

  </class>

  <class catalog="test" name="test.Person" table="PersonsAUD" entity-name="PersonAUD">

    <id name="idAudit" type="int">
      <column name="IdAudit"/>
      <generator class="increment"/>
    </id>      

    <property name="name" type="string">
      <column length="30" name="Name" not-null="true"/>
    </property>
    <property name="action" type="string">
      <column length="10" name="Action" not-null="true"/>
    </property>
    ...
  </class>

I'm trying to save this object in the two tables like this:

session.save("Person", person);
session.save("PersonAUD", person);

But only the first row is inserted, not the audit row; probably hibernate check the person's state and confirms that is already saved.

Any chance to force hibernate to save in both tables the same object?

Thanks in advance.

2条回答
戒情不戒烟
2楼-- · 2019-05-10 00:42

In your second mapping change this

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

to

<id name="id" type="int">
查看更多
啃猪蹄的小仙女
3楼-- · 2019-05-10 00:53

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

查看更多
登录 后发表回答