簡體   English   中英

自引用實體插入兩條記錄

[英]Self-Referencing entity inserts two records

我有一個引用自己的“類別”實體。

@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 | 位置| 子彈頭 PARENT_ID |

| 1 | 1 | 1 | 1 | 2 |

| 2 | 空| 0 | 空| 空|

我想插入PARENT_ID為null的“一個”記錄,但它會插入記錄(id = 2)和記錄(id = 1)作為子記錄。

我使用Spring-Data JPA接口API保存記錄:

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

將您的parent映射更改為以下內容,不會。

@ManyToOne
private Category parent;

觀察到此行為的原因是, CascadeType.PERSIST將為您創建一個新的空類別,而不是Hibernate而是僅創建具有空父級的子記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM