休眠4:一个类映射两个表-如何在两个表上持久化一个对象? [英] Hibernate 4: One class mapping Two tables - How to persist one object on both tables?

查看:113
本文介绍了休眠4:一个类映射两个表-如何在两个表上持久化一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个类的Person映射两个表:Persons和PersonsAUD(审核):

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?

谢谢.

推荐答案

我强烈建议不要这样做.这很令人困惑.不仅对于Hibernate,而且以后还会为您(其他开发人员)带来更多问题.为了更清楚一点,请让我们尝试在POJO实体(不是动态模型)中考虑该问题

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 

会话将仅调用一次插入,因为只有一个实例.具有一个唯一标识符的一个对象.除了 person 之外,不能将其评估为其他任何值.

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.

动态模型也发生了同样的情况.插入后,尝试观察您的HashMap person .应该有一个键"$type$",该键应该告诉您该实例是如何评估的(作为 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.

如果您需要将一组信息保存到两个表中,请使其更符合ORM样式.例如. clone person 放入new HashMap()并保存两个独立的实体

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

这篇关于休眠4:一个类映射两个表-如何在两个表上持久化一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆