2016-07-31 30 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