多对多:当还有另一个'孩子'时,'父母'被删除

时间:2011-08-05 06:39:19

标签: java hibernate hibernate-mapping

我有一对多关系,其中一方的两条记录在另一方具有相同的父级(关系的所有者)。当我删除两个记录中的一个时,也会删除父记录和可加入记录。我不想要这个。我希望只要另一方有孩子,就不会删除父母。

我有以下数据:

Table A                                      
SID | NAME                                 
-----------------------               
90  | xyz                                     
-----------------------               
91  | abc                                 

Table AB                                    
A_SID | B_SID
-----------------------               
 90     | 5                                     
-----------------------               
 91     | 5                             

Table B                                    
SID | NAME
-----------------------               
5    | lala                                                          

这就是hibernate映射

mapping of class A on table A:
<hibernate-mapping ...

        <set name="setOfBs" table="AB" inverse="true" cascade="delete-orphan">
            <key column="A_SID" not-null="true" />
            <many-to-many column="B_SID" class="B"/>
        </set>
...
</hibernate-mapping>

mapping of class B on table B:
<hibernate-mapping ...

        <set name="setOfAs" table="AB" lazy="false">
            <key column="B_SID" not-null="true" />
            <many-to-many column="A_SID" class="A"/>
        </set>
...
</hibernate-mapping>

删除SID为'90'且NAME为'xyz'的对象后,我的数据如下所示:

05/08/2011 07:29:43,259 [DEBUG] SQL - delete from AB where B_SID=?
05/08/2011 07:29:43,259 [TRACE] BasicBinder - binding parameter [1] as [BIGINT] - 5
05/08/2011 07:29:43,264 [DEBUG] SQL - delete from B where SID=? and OBJECT_VERSIE=?
05/08/2011 07:29:43,265 [TRACE] BasicBinder - binding parameter [1] as [BIGINT] - 5
05/08/2011 07:29:43,265 [TRACE] BasicBinder - binding parameter [2] as [BIGINT] - 0
05/08/2011 07:29:43,275 [DEBUG] SQL - delete from A where SID=? and OBJECT_VERSIE=?
05/08/2011 07:29:43,275 [TRACE] BasicBinder - binding parameter [1] as [BIGINT] - 90
05/08/2011 07:29:43,275 [TRACE] BasicBinder - binding parameter [2] as [BIGINT] - 0



Table A                                      
SID | NAME                                 
-----------------------                           
91  | abc                                 

Table AB                                    
A_SID | B_SID
-----------------------                                    

Table B                                    
SID | NAME
-----------------------   

我希望表B中的记录不会被删除,因为它不是一个孤儿。我做错了什么?

1 个答案:

答案 0 :(得分:0)

在A Entity中使用它     private List Bs = new ArrayList(0);

@ManyToMany(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
@JoinTable(name = "AB", joinColumns = { @JoinColumn(name = "A", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "B", nullable = false, updatable = false) })
public List<B> getBs() {
    return this.Bs;
}

public void setBs(List<B> Bs) {
    this.Bs = Bs;
}