2014-02-20 25 views
0

我有一個包含子代和父代的自引用實體。我有一個連接表來存儲相互排斥的兄弟姐妹。當在數據庫中創建的實體,我得到這個例外...JPA與兄弟連接表相關的自引用實體

造成的:org.springframework.orm.jpa.JpaSystemException:org.hibernate.PersistentObjectException:通過堅持

主表脫離實體將有

ID Text Parent 
1 ABC null 
2 CBD 1 
3 XYZ 1 

加入表應該有

entity sibling 
2  3 

是實體映射關係是否正確?

@Entity 
public class TestEntity { 
    @id 
    @GeneratedValue 
    private int id; 
    private String Text; 
    @ManyToOne 
    private TestEntity parent; 

@OneToMany(cascade=CascadeType.ALL) 
@JoinTable(name="mutuallyExclusiveSiblings", 
     joinColumns={@JoinColumn(name="entity", referencedColumnName="id")}, 
     inverseJoinColumns={@JoinColumn(name="sibling", referencedColumnName="id")}) 
     private Set<TestEntity> exclusiveSiblings; 


} 

任何幫助實現這一點表示讚賞。謝謝。

+0

您可能想要發佈用於保存實體的代碼片段。 – tmarwen

+0

您在分離的實體上(即在已經有ID的實體上)調用persist()。那就是問題所在。 –

+0

對不起,由於專有機密信息問題,我無法發佈實際代碼......在這裏是上述示例的代碼。謝謝你的幫助。 TestEntity te = new TestEntity(); (3)te.setId(4); te.setParent(null); Set exsib = new HashSet (); (exsib); te.setExclusiveSiblings(exsib); List ret = new ArrayList (); ret = testEntityService.getByText(「XXX」); (TestEntity t:ret){ te.getExclusiveSiblings()。add(t); } testEntityService.createRecord(te); – user3154305

回答

0

CascadeType.ALL意味着與某些TestEntity兄弟姐妹通過TestEntity繼續調用將觸發測試實體和兄弟測試實體的插入。

如果其中任何一個已經作爲Id填充,將導致錯誤,因爲persist僅適用於數據庫中尚不存在的新創建的實體。

因此,如果您要將新的TestEntity鏈接到數據庫中的現有兄弟,那麼最好不要在第一次添加子節點時繼續調用新的TestEntity

此時,新的TestEntity將被勾選,並且您可以將其鏈接到現有的兄弟,當會話刷新時將觸發關聯表中的插入操作。

+0

你在我的一個測試中都是對的,兩個表都被插入了。用例是我想插入一個新的TestEntity與id 4,但它會有現有的互斥兄弟,例如id 2。在創建新的TestEntity 4應創建TestEntity表和ids 4和2應創建連接表。謝謝。 – user3154305

+0

我編輯了問題和答案,看看 –

+0

工作。謝謝你的幫助。 – user3154305