Hibernate为列设置空值,而不是在saveOrUpdate()上删除整行

时间:2011-07-01 20:58:17

标签: java database hibernate

我有一个CatastrophePerilAssoc类控制Catastrophe类到Peril类的映射,表CAT_PERIL_ASSOC有三行:id(主键,自动生成),catastrophe.id(映射到灾难),和peril.id(映射到危险)

当我添加或删除关联时,会在表中创建新的关联(行),这很好。但是,hibernate不会删除旧行,而是将catastrophe.id的值设置为null。有没有办法告诉hibernate删除这些行?请注意,我不想删除在其他地方使用的实际对象,但我只是想从这个特定的表中删除它们。

查看sql日志,我可以确认它是否将列值设置为null:

update CAT_PERIL_ASSOC set CATASTROPHE_TYPE_ID=null where CATASTROPHE_TYPE_ID=?

Hbm文件:

<hibernate-mapping package="com.nature">
    <class name="com.nature.CatastrophePerilAssoc" table="CAT_PERIL_ASSOC">
        <id name="id" type="string">
            <column name="id" length="32" />
            <generator class="uuid.hex" />
        </id>
        <many-to-one name="catastrophe" class="com.nature.catastrophe">
               <column name="CATASTROPHE_TYPE_ID" />
         </many-to-one>
         <many-to-one name="peril" class="com.nature.peril">
                <column name="PERIL_ID" />
         </many-to-one>

    </class>
</hibernate-mapping>

Java类:

public class CatastrophePerilAssoc  {

    private Catastrophe cat; 
    private Peril peril;

    public Catastrophe getCatastrophe() {
        return cat;
    }
    public void setCatastrophe(Catastrophe cat) {
        this.cat = cat;
    }

    public Peril getPeril() {
        return peril;
    }
    public void setPeril(Peril peril) {
        this.peril = peril;
    }
}

更新关联的代码:

public void saveCatPerilAssoc(Catastrophe cat) {

    Criteria polquery = getSession(false).createCriteria(cat.getClass());
    polquery.add(Restrictions.eq("name", cat.getName()).ignoreCase());

    if (cat.getId() != null) {
        polquery.add(Restrictions.ne("id", cat.getId()));
    }

    if (polquery.list().size() > 0) {
        //throw error
    }

    getSession(false).saveOrUpdate(cat);
}

1 个答案:

答案 0 :(得分:1)

您需要使用名为 delete-orphan 的级联类型。您需要在Catastrophe和Peril类上配置cascade-orphan,因此如果其中任何一个删除了关联,这也将从连接表中删除该条目。

检查documentation的这一部分,更好地解释了这个级联。

还有一个问题。为什么使用CatastrophePerilAssoc连接表? Hibernate管理多对多关系,因此不需要创建像CatastrophePerilAssoc这样的实体。