Hibernate孤儿删除似乎不起作用

时间:2013-11-18 01:05:24

标签: java database spring hibernate

有人可以解释为什么orphan删除属性在以下示例代码中不起作用?测试中的最后一次检查失败了...在测试结束时,数据库包含父项和子项,但它们之间的关系消失了。所以孩子真的是孤儿,但仍然没有被清除。

public class ParentDao3Test {
    @Autowired private ParentDao parentDao;
    @Autowired private ChildDao childDao;

    @Test
    public void testCRUD() {
        DBChild child = new DBChild("John");
        DBParent parent = new DBParent();
        parent.addChild(child);

        parentDao.persist(parent);

        assertTrue(parent.getId() > 0);
        assertTrue(parent.getChilds().size() == 1);
        assertTrue(child.getId() > 0);

        parent.removeChild(child);

        parentDao.flush(); 

        //succeed
        assertTrue(parent.getChilds().size() == 0);  

        //fail here because the child doesn't get cleared from the DB    
        assertNull(childDao.findById(child.getId())); 

    }
}

@Entity
@Table(name = "Parent")
public class DBParent {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private long id;

    @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL}, orphanRemoval=true)
    @JoinColumn(nullable=true)
    @JoinTable
    private Set<DBChild> childs = new HashSet<DBChild>();

    @Column(name = "VERSION")
    @Version
    private Integer version;

    public void addChild(DBChild child) {
        this.childs.add(child);
    }

    public void removeChild(DBChild child) {
        this.childs.remove(child);
    }
}

@Entity
@Table(name = "child")
public class DBChild {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private long id;

    @Column(name="name", nullable = false, length=1024)
    private String name;

    @Column(name = "VERSION")
    @Version
    private Integer version;
}


解决方法: 通过在持久化之后添加一个flush似乎使测试通过。基本上似乎只要关系没有刷入数据库,孤立删除属性似乎不起作用。这让我觉得孤儿删除不适用于第一级缓存。

0 个答案:

没有答案