我有两节课:

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;
    }
}


然后,我尝试在主方法中保存departmentemployees

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;

10-01 22:23