我有两个类StudentSubject

学生

@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

@Column(name = "full_name")
private String fullName;

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "students")
private Set<Subject> subject;

//Getters & setters
}


学科

@Entity
@Table(name = "subjects")
public class Subject {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

@Column(name = "subject_name")
private String name;

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Student> students;
//Getters & setters
}


当我试图保存注册了多个科目的学生时,JoinTable中没有任何记录。

我的代码保存实体:

    Subject subject = new Subject();
    subject.setName("JAVA");

    Subject subject2 = new Subject();
    subject2.setName("C");

    Subject subject3 = new Subject();
    subject3.setName("C++");

    Student student = new Student();
    student.setFullName("dibya");

    Set<Subject> subjects = new HashSet<>();
    subjects.add(subject2);
    subjects.add(subject);
    subjects.add(subject3);

    student.setSubject(subjects);

    session.saveOrUpdate(student);


请告诉我我在哪里做错了。

最佳答案

找到了解决我问题的方法。

它不是与配置。只需使用mappedBy属性ManyToMany关系就可以实现。

在我的程序中,保存学生后我添加了session.saveOrUpdate(subject);

这解决了我的问题。 :)

关于java - 如何在 hibernate 状态下更新JoinTable,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25196261/

10-11 03:35