从关联中删除已删除的对象而不将其删除在数据库中

时间:2017-02-28 16:05:11

标签: hibernate hibernate-mapping hbm

当我尝试运行此代码时,我有一个名为DashboardPage的实体,其中包含DashboardPageItem列表:

for(DashboardPage dp : dashboard.getPages()){
            if(dp.getIndex() == dashboardPage.getIndex()){
                dp.getDashboardPageItems().clear();
                Iterator<DashboardPageItem> itDashboardPageItem = dp.getDashboardPageItems().iterator();
                while (itDashboardPageItem.hasNext()) {
                   DashboardPageItem dpi = itDashboardPageItem.next();
                   itDashboardPageItem.remove();
                }

            }
        }

我收到此错误消息:

deleted object would be re-saved by cascade (remove deleted object from associations): [com.dashboard.entity.DashboardPage#22]

当我搜索类似的问题时,我发现我必须使用session.delete(),但这会从数据库中删除该对象,我只想将其从列表中删除。

这是我班级的hbm:

DashboardPage:

<class name="DashboardPage" table="t_dashboard_page_dpa">
        <id name="id" column="dpa_id">
            <generator class="native"/>
        </id> 

        <property name="name" column="dpa_name"/>
        <property name="index" column="dpa_index"/>
        <property name="model" column="dpa_model"/>

        <many-to-one name="dashboard" 
                     column="fk_das_id"
                     foreign-key="das_id"
                     not-null="false"
                     lazy="false"/>

        <bag table="t_dashboard_page_item_dpi" name="dashboardPageItems" inverse="true" lazy="true" cascade="all,delete-orphan">
            <key column="fk_dpa_id" not-null="true" unique="false" foreign-key="dpa_id"/>
            <one-to-many class="com.lomaco.cloud.DashboardPageItem"></one-to-many>    
        </bag>


    </class>

DashboardPageItem:

<class name="DashboardPageItem" table="t_dashboard_page_item_dpi">
        <id name="id" column="dpi_id">
            <generator class="native"/>
        </id> 

        <property name="position" column="dpi_position"/>

        <many-to-one name="dashboardPage" 
                     column="fk_dpa_id"
                     foreign-key="dpa_id"
                     not-null="false"
                     lazy="false"
                    cascade="all"/>

        <many-to-one name="widget" 
                     column="fk_wid_id"
                     foreign-key="wid_id"
                     not-null="false"
                     lazy="false"/>

    </class>

我该如何解决这个问题?

编辑:

这段代码只是我正在做的事情的一部分,所以我不希望数据库受到我所做的更改的影响,但在另一部分我想调用{{1}这将保存我所做的所有修改。

1 个答案:

答案 0 :(得分:0)

如果您只想级联由session.delete()显式调用的删除,则代替此:

cascade="all,delete-orphan"

仅限使用

cascade="all"

delete-orphan cascade属性的工作方式是,当您只是从托管集合中删除某个项目时...它会在事务结束时被删除。