更新对象时的删除语句错误

时间:2012-12-18 16:55:07

标签: java hibernate

在我的场景中,我有2个表:专辑和图像(关系是一对多)。

这是简化的映射:

<hibernate-mapping>
  <class name="Album" table="album">
    <id name="id" column="album_id" type="int">
        <generator class="sequence">
            <param name="sequence">TestObject_seq</param>
        </generator>
    </id>
    <set name="image" table="image" order-by="orderBy">
        <key column="album_id" />
        <composite-element class="Image">
            <property name="caption" column="caption" type="string"/>
            <property name="path" column="path" type="string"/>
            <property name="orderBy" column="orderBy" type="int"/>
        </composite-element>
    </set>  
    </class>
</hibernate-mapping>

我这样做: 1.在db中查找对象, 2.从集合中删除一些记录, 3.调用saveOrUpdate。

Album album = dao.getAlbum("Name of album");

Set<Image> imagesToRemove = getImagesToRemove();
album.getImages().removeAll(imagesToRemove);

dao.saveOrUpdate(album);
dao.flushAndClear();

在表格图像中的某些值为空之前,一切都还可以。例如,标题具有空值。

在日志中我可以看到:

DEBUG SQL:292 - delete from image where album_id=? and caption=? and path=? and orderBy=?
DEBUG AbstractBatcher:343 - preparing statement
DEBUG IntegerType:59 - binding '463' to parameter: 1
DEBUG StringType:52 - binding null to parameter: 2
...

在这种情况下,删除语句不会删除任何记录。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

实际上你并没有删除孤儿。当您通过删除它们作为孤儿在数据库中存在的实体来更新对象时。 试试这个。

<set name="image" table="image" cascade="all-delete-orphan" order-by="orderBy">
    <key column="album_id" ></key>
    <composite-element class="Image">
        <property name="caption" column="caption" type="string"/>
        <property name="path" column="path" type="string"/>
        <property name="orderBy" column="orderBy" type="int"/>
    </composite-element>
 </set>