代码之家  ›  专栏  ›  技术社区  ›  Konrad Garus

Hibernate:复合元素导致每次提交时delete+insert

  •  3
  • Konrad Garus  · 技术社区  · 14 年前

    <hibernate-mapping package="trx.domain">
        <class name="Master" table="master" dynamic-update="true" dynamic-insert="true">
    
            <set name="attributes" table="attribute" lazy="true"
                cascade="all" batch-size="10">
                <cache usage="nonstrict-read-write" />
                <key>
                    <column name="master_id" />
                </key>
                <composite-element class="Attribute">
                    <many-to-one name="type" class="AttributeType"
                         not-null="true" column="attribute_type_id" lazy="false" />
                    <property name="value">
                        <column name="value" />
                    </property>
                </composite-element>
            </set>
        </class>
    </hibernate-mapping>
    

    如果我只是扫描 attributes 在没有任何更新的情况下,Hibernate仍然会执行一批 delete insert

    Hibernate: delete from attribute where master_id=? and attribute_type_id=?
    Hibernate: delete from attribute where master_id=? and attribute_type_id=?
    Hibernate: insert into attribute (master_id, attribute_type_id, value) values (?, ?, ?)
    Hibernate: insert into attribute (master_id, attribute_type_id, value) values (?, ?, ?)
    

    为什么会这样?如何预防?

    1 回复  |  直到 14 年前
        1
  •  4
  •   Tadeusz Kopec for Ukraine yespbs    14 年前

    根据 Hibernate Reference

    由于集合的结构,Hibernate不会在元素“更改”时更新行。对集合的更改总是通过插入和删除单个行来实现的。

    如果Hibernate试图更新你的集合,即使你不修改它,也许你的 equals hashcode Attribute 上课都坏了?