gpt4 book ai didi

java - TransientObjectException 即使我设置了cascade=CascadeType.ALL

转载 作者:行者123 更新时间:2023-12-02 04:20:15 25 4
gpt4 key购买 nike

我有两个类:

Employee.java

@Entity
@Table
public class Employee {
@Id
@GeneratedValue
private Long id;

private String name;

@ManyToOne
private Department department;

public Employee() {}

public Employee(String name, Department department) {
this.name = name;
this.department = department;
}


public Employee(String name) {
this.name = name;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Department getDepartment() {
return department;
}

public void setDepartment(Department department) {
this.department = department;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", department="
+ department.getName() + "]";
}

}

部门.java

@Entity
@Table
public class Department {

@Id
@GeneratedValue
private Long id;


private String name;

@OneToMany(mappedBy="department",cascade=CascadeType.ALL)
private List<Employee> employees = new ArrayList<Employee>();

public Department() {
super();
}
public Department(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}

然后我尝试在主方法中保存部门员工:

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

Department department = new Department("java");
//session.save(department); //throw org.hibernate.TransientObjectException if I comment the line

session.save(new Employee("Jakab Gipsz",department));
session.save(new Employee("Captain Nemo",department));

session.getTransaction().commit();

没成功。它抛出了一个错误:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.learn.hibernate.Department

但是如果我取消注释行 session.save(department);,一切都会正常工作。为什么?我已经设置了 cascade=CascadeType.ALL,因此它应该自动保存 department 而不会引发任何错误。我错过了什么吗?

最佳答案

当您保存员工时,不会保存部门,因为没有级联。如果你想要这样,你需要在 Employee 类中添加一个级联。

@ManyToOne(cascade = CascadeType.save)
private Department department;

关于java - TransientObjectException 即使我设置了cascade=CascadeType.ALL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32863051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com