Hibernate OneToMany关系不会映射新数据

时间:2016-12-25 07:40:09

标签: java spring hibernate

我有两个实体课程和CourseUser。使用OneToMany注释映射到CourseUser的课程。在课程中的CourseUser列表中添加CourseUser并更新后,在课程表中显示新行,但它没有映射到课程。如果我在更新后调用课程中的课程,那么它将是空的。

@Entity
@Table(name = "COURSES")
public class Courses{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "course_id")
    private int course_id;

    @Column(name = "course_name", nullable = false)
    private String courseName;

    @Autowired
    @OneToMany(mappedBy = "course", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<CourseUser> courseUsers = new HashSet<>(0);

CourseUser实体:

@Entity
@Table(name = "COURSE_USERS",
    uniqueConstraints = {@UniqueConstraint(columnNames = {"course_name", "user_name"})})
public class CourseUser {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ev_id")
    private int ev_id;


    @Column(name = "course_name", nullable = false)
    private String courseName;

    @Column(name = "user_name", nullable = false)
    private String userName;

    @Column(name = "course_role")
    private String courseRole;

    @Column(name = "grade")
    private int grade ;

    @ManyToOne
    @JoinColumn(name = "course_id")
    private Courses course;

这是我在课程中添加新课程的方法:

Courses course = courseDAO.getCourse(id);
Set<CourseUser> courseUsers = course.getCourseUsers();
CourseUser newUser = new CourseUser();
            newUser.setUserName(name);
            newUser.setCourseRole(role);
            newUser.setCourseName(course.getCourseName());
            courseUsers.add(newUser);
            course.setCourseUsers(courseUsers);
            update(course);

这里是CoursesDAO更新方法:

public void update(Courses course) {

        Session session = sf.openSession();
        Transaction transaction = session.beginTransaction();
        session.merge(course);
        session.flush();
        transaction.commit();
        session.close();
    }

1 个答案:

答案 0 :(得分:0)

首先,您必须保存由id引用的实体。 在您的情况下,您必须先保存CourseUser,然后将其添加到Course

例如:

Courses course = courseDAO.getCourse(id);
Set<CourseUser> courseUsers = course.getCourseUsers();
CourseUser newUser = new CourseUser();
newUser.setUserName(name);
newUser.setCourseRole(role);
newUser.setCourseName(course.getCourseName());
// this row is very important
// after thus operation newUser will have an id to be referenced
courseUserDto.save(newUser);
courseUsers.add(newUser);
course.setCourseUsers(courseUsers);
update(course);

此外,您编写了一些冗余代码:

Set<CourseUser> courseUsers = course.getCourseUsers();
// ...
course.setCourseUsers(courseUsers);

course已存储对courseUsers的引用。