Java 子对象不能从父对象分离
我的文档实体类是Java 子对象不能从父对象分离,java,hibernate,jpa,spring-data-jpa,Java,Hibernate,Jpa,Spring Data Jpa,我的文档实体类是 @Entity @Table(name="Document_Directory") public class DocumentDirectoryEntity{ private int id; private String name; private DocumentDirectoryEntity parentDirectory; private List<DocumentDirectoryEntity> ch
@Entity
@Table(name="Document_Directory")
public class DocumentDirectoryEntity{
private int id;
private String name;
private DocumentDirectoryEntity parentDirectory;
private List<DocumentDirectoryEntity> childDirectoryList;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name", length=250, nullable= false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="parent_dir_id")
public DocumentDirectoryEntity getParentDirectory() {
return parentDirectory;
}
public void setParentDirectory(DocumentDirectoryEntity parentDirectory) {
this.parentDirectory = parentDirectory;
}
@OneToMany(mappedBy="parentDirectory", cascade=CascadeType.ALL, fetch=FetchType.LAZY, orphanRemoval=true)
public List<DocumentDirectoryEntity> getChildDirectoryList() {
return childDirectoryList;
}
public void setChildDirectoryList(List<DocumentDirectoryEntity> childDirectoryList) {
this.childDirectoryList = childDirectoryList;
}
}
我想删除文档,但在删除之前,我想更改其子文档的父文档。但是我做不到。代码是:-
DocumentDirectoryEntity documentDirectoryEntity = documentDirectoryDao.findById(1);
DocumentDirectoryEntity documentDirectoryEntity1 = documentDirectoryDao.findById(2);
List<DocumentDirectoryEntity> childDirectoryList = documentDirectoryEntity.getChildDirectoryList();
DocumentDirectoryEntity childDirectory = childDirectoryList.get(0);
childDirectory.setParentDirectory(documentDirectoryEntity1);
documentDirectoryDao.update(childDirectory);
documentDirectoryDao.delete(documentDirectoryEntity);
当我删除对象documentDirectoryEntity时,childDirectory行也会被删除。您也必须从父目录中删除chile。我还尝试了documentDirectoryEntity.getChildDirectoryList.removechildDirectory;documentDirectoryDao.updatedocumentDirectoryEntity;在documentDirectoryDao.deletedocumentDirectoryEntity;之前;。但问题仍然存在,您是否在childDirectory上对所有对象进行了级联?是的,使用orphanRemoving cascade=CascadeType.all,fetch=FetchType.LAZY,orphanRemoving=true