如何修复“传递给持久性的独立实体"?Springboot +休眠 [英] How to fix "Detached entity passed to persist" Springboot+Hibernate
问题描述
伙计们,我尝试过这里或在其他网站中提出的不同方法来解决此错误,虽然之前已经解决过,但在另一种情况下,但这似乎很复杂.,这是一个名为部门的实体,该实体与自己之间具有oneToMany关系,因此部门可以具有一个或多个子部门,而一个部门应该只有一个且只有一个上级部门.
guys i've tried different methods proposed here or in an other websites to fix this error, i've fixed it before but in another case, but this one seems a complicated one. , an entity named department which have a oneToMany relation with it self , so the departement can have one or many subDepartments , and a department should have one and only one parent department.
部门实体:
@Entity
@Table(name = "DEPARTMENTS")
public class Department {
@Id
@Column(name = "dep_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long depId;
private String depName;
@ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "supDep", referencedColumnName = "dep_Id")
@JsonIgnoreProperties(value ={"departments","users"} , allowSetters = true)
private Department supDep;
@OneToMany(mappedBy = "supDep", orphanRemoval = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnoreProperties(value ={"supDep","users"} , allowSetters = true)
private List<Department> departments = new ArrayList<>() ;
Constructors & getters &setters...
}
DepartmentRepository:
DepartmentRepository:
@Repository
public interface DepartmentRepository extends JpaRepository<Department,Long> {
Department findByDepName(String name);
}
DepartmentService接口:
DepartmentService Interface :
public interface DepartmentService {
Department add(Department department);
Department update(Department department, Long id);
void delete(long id);
List<Department> findAll();
Department findByName(String name);
Department findById(Long id);
User getChefDep(Long idDep);
}
DepartmentServiceImplement:
DepartmentServiceImplement :
@Service(value = "departmentService")
public class DepartmentServiceImpl implements DepartmentService {
....
@Override
public Department add(Department department) {
Department newDep = new Department();
if(department.getDepId() != 0)
newDep.setDepId(department.getDepId());
newDep.setDepName(department.getDepName());
newDep.setChefDep(department.getChefDep());
newDep.setSupDep(department.getSupDep());
newDep.setDepartments(department.getDepartments());
newDep.setUsers(department.getUsers());
return departmentRepository.save(department);
}
...
}
DepartmentController ADD方法:
DepartmentController ADD method :
@RestController
@CrossOrigin("*")
@RequestMapping("/department/")
public class DepartmentController {
...
@PostMapping("add")
public Department add(@RequestBody Department department) {
return departmentService.add(department);
}
...
}
无论如何,当我用邮递员添加一个新部门时,它可以工作并且该部门保存在DATABASE中:
anyway, when i add a new department with postman it works and the department is saved in DATABASE :
{
"depName": "marketing",
"supDep": null,
"departments": []
}
当我用DATABASE中不存在的supDep添加新部门时,它也可以工作,并且两个实体都保存在DATABASE中:
and when i add a new department with a supDep that doesn't exist in DATABASE it works too and the both entities are saved in DATABASE :
{
"depName": "Security",
"supDep":
{
"depName": "IT",
"supDep": null,
"departments": [],
"chefDep": 0,
}
}
但是当我添加一个通过supDep的新部门时,确实存在一个部门:
but when i add a new department passing supDep a department that does exist :
{
"depName": "sub-marketing",
"supDep":
{
"depId": 1,
"depName": "marketing"
}
}
它抛出了这个烦人的错误:
it throws this annoying error :
{
"timestamp": "2020-03-17T14:49:40.071+0000",
"status": 500,
"error": "Internal Server Error",
"message": "detached entity passed to persist: com.ats.remotetimemanager.Model.Department; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.ats.remotetimemanager.Model.Department",
"trace": "org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.ats.remotetimemanager.Model.Department; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.ats.remotetimemanager.Model.Department\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:319)\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)\r\n\tat org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)\r\n\tat org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)\r\n\tat org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178)
推荐答案
吸气剂&设置者:
the getters & setters :
public long getDepId() {
return depId;
}
public void setDepId(long depId) {
this.depId = depId;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
public Department getSupDep() {
return supDep;
}
public void setSupDep(Department supDep) {
this.supDep = supDep;
}
public List<Department> getDepartments() {
return departments;
}
public void setDepartments(List<Department> departments) {
this.departments = departments;
}
public long getChefDep() {
return chefDep;
}
public void setChefDep(long chefDep) {
this.chefDep = chefDep;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
@Override
public String toString() {
return "Department{" +
"depId=" + depId +
", depName='" + depName + '\'' +
", supDep=" + supDep +
", departments=" + departments +
", chefDep=" + chefDep +
'}';
}
}
这篇关于如何修复“传递给持久性的独立实体"?Springboot +休眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!