Java Hibernate孤立项删除不';好像不行
有人能解释一下为什么孤儿移除属性在下面的示例代码中不起作用吗?测试中的最后一次检查失败。。。在测试结束时,数据库包含父级和子级,但它们之间的关系消失了。所以这孩子真的是孤儿,但仍然没有被清除Java Hibernate孤立项删除不';好像不行,java,database,spring,hibernate,Java,Database,Spring,Hibernate,有人能解释一下为什么孤儿移除属性在下面的示例代码中不起作用吗?测试中的最后一次检查失败。。。在测试结束时,数据库包含父级和子级,但它们之间的关系消失了。所以这孩子真的是孤儿,但仍然没有被清除 public class ParentDao3Test { @Autowired private ParentDao parentDao; @Autowired private ChildDao childDao; @Test public void testCRUD()
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;
}
公共类ParentDao3Test{
@自动连接的私有ParentDao ParentDao;
@自动连接的私有ChildDao ChildDao;
@试验
公共void testCRUD(){
DBChild=新DBChild(“约翰”);
DBParent parent=新的DBParent();
parent.addChild(child);
parentDao.persist(parent);
assertTrue(parent.getId()>0);
assertTrue(parent.getChilds().size()=1);
assertTrue(child.getId()>0);
父母。removeChild(子女);
parentDao.flush();
//成功
assertTrue(parent.getChilds().size()=0);
//此处失败,因为未从数据库中清除子项
assertNull(childDao.findById(child.getId());
}
}
@实体
@表(name=“Parent”)
公共类DBParent{
@身份证
@列(name=“id”)
@GeneratedValue(策略=GenerationType.AUTO)
私人长id;
@OneToMany(fetch=FetchType.EAGER,cascade={CascadeType.ALL},orphanRemoving=true)
@JoinColumn(nullable=true)
@可接合
private Set childs=new HashSet();
@列(name=“VERSION”)
@版本
私有整数版本;
公共void addChild(DBChild-child){
this.childs.add(child);
}
public void removeChild(DBChild-child){
此.childs.remove(child);
}
}
@实体
@表(name=“child”)
公共类DBChild{
@身份证
@列(name=“id”)
@GeneratedValue(策略=GenerationType.AUTO)
私人长id;
@列(name=“name”,null=false,长度=1024)
私有字符串名称;
@列(name=“VERSION”)
@版本
私有整数版本;
}
解决方法: 在persist之后添加一个flush似乎可以使测试通过。基本上,只要关系未刷新到数据库中,孤立删除属性似乎就不起作用。这让我觉得孤立删除在一级缓存上不起作用