2016-07-31 75 views
0

我有一個引用self的「Category」實體。Self-Referencing實體插入兩條記錄

@Entity 
public class Category extends NamedEntity { 

    private String slug; 

    private int position; 

    @ManyToOne(cascade = { CascadeType.PERSIST }) 
    private Category parent; 

    @OneToMany(mappedBy = "parent") 
    private Set<Category> children = new HashSet<Category>(); 

    ... getters/setters ... 

當我保存它沒有父實體時,它把 「二」 記載:

| ID | NAME |位置| SLUG | PARENT_ID |

| 1 | 1 | 1 | 1 | 2 |

| 2 | null | 0 | null | null |

我想要插入PARENT_ID爲空的「one」記錄,但它插入記錄(id = 2)和記錄(id = 1)作爲孩子。

我節省使用Spring的數據JPA接口(API)的記錄:

public interface CategoryRepository extends Repository<Category, Long> { 
    public Category findById(Long id) throws DataAccessException; 
    public Category save(Category category) throws DataAccessException; 
} 

回答

0

更改映射parent以下內容並不會。

@ManyToOne 
private Category parent; 

你觀察到這種現象的原因是,CascadeType.PERSIST將創建一個新的空類別你,而不是僅僅Hibernate的創建與null'd父子記錄。

+0

當我刪除級聯選項,發生「TransientPropertyValueException異常」。這就是爲什麼我把'''CascadeType.PERSIST'''。 異常描述是'''對象引用一個未保存的瞬態實例 - 保存瞬態實例beforeQuery flushing'''。 謝謝。 – nasiajai

+0

如果您明確將該值設置爲「null」,則不應該抱怨。 – Naros

+0

我很抱歉,我不得不說它的結果是一樣的。 – nasiajai