无法使用hibernate.save()保存数据

时间:2016-09-26 08:07:28

标签: java angularjs spring hibernate cascade

我正在尝试添加具有员工信息,角色和主题的Staff对象。下面的代码仅保存Staff数据而不保存其关联的集合数据。 我试图调试它,但不明白这个问题。在保存到数据库之前,staff对象具有角色和主题,但它们不会保存在DB中。令人惊讶的是,类似的代码在保存课程表数据时正在工作;但是,课程也有主题类的集合。

在我看来,Subjects有Course对象可能会产生问题,我不知道为什么。请告知如何解决它。

完整项目可在GitHub上使用(https://github.com/ravinain/practice/tree/master/Java/Spring/SchoolProject

Staff.java

@Entity
@Table
public class Staff extends Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private double salary;

    @OneToMany(mappedBy = "staff", fetch=FetchType.EAGER)
    @Cascade({ CascadeType.ALL})
    private Set<Role> roles = new HashSet<Role>();

    @ManyToMany(mappedBy = "staffs", fetch=FetchType.EAGER)
    @Cascade({CascadeType.ALL})
    private Set<Subject> subjects = new HashSet<Subject>();

Role.java

@Entity
@Table
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @NotNull
    private int id;
    private String name;

    @ManyToOne
    @JoinTable(name = "role_staff", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "staff_id", referencedColumnName = "id"))
    @JsonIgnore
    private Staff staff;

Subject.java

@Entity
@Table
public class Subject implements Comparable<Subject>{

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String description;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "subject_staff", joinColumns = @JoinColumn(name = "subject_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "staff_id", referencedColumnName = "id"))
    @JsonIgnore
    private Set<Staff> staffs = new HashSet<Staff>();

    @ManyToMany(mappedBy = "subjects", fetch = FetchType.EAGER)
    @Cascade({ CascadeType.DELETE, CascadeType.SAVE_UPDATE })
    @JsonIgnore
    private Set<Course> courses = new HashSet<Course>();

    @ManyToMany(mappedBy = "subjects", fetch = FetchType.EAGER)
    @Cascade({ CascadeType.DELETE, CascadeType.SAVE_UPDATE })
    @JsonIgnore
    private Set<Student> students = new HashSet<Student>();

DAO代码:

public Staff addStaff(Staff staff) {
    Session session = sessionFactory.getCurrentSession();
    session.save(staff);
    return staff;
}

POST请求:

{"name":"New Test","age":22,"gender":"Female","salary":12000,"roles":[{"id":3,"name":"Teacher"}],"subjects":[{"id":1,"description":"Math"},{"id":2,"description":"English"}]}

0 个答案:

没有答案