这个问题通常是由于使用JPA中的@JoinTable注释创建了一个中间表,以便处理多对多关系并增加了额外的列。在保存实体时,添加的额外列被正确设置,但当更新实体时,这些列没有被更新。这是因为JPA不会自动更新中间表的列。
为了解决这个问题,可以使用@PreUpdate注释在更新前手动更新中间表的列。下面是一个具有额外列的Many to Many关系并使用Jointable的代码示例:
@Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
private String name;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
private Set courses = new HashSet<>();
@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
private Set studentCourses = new HashSet<>();
// Constructors, getters, and setters
}
@Entity public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
private String name;
@ManyToMany(mappedBy = "courses")
private Set students = new HashSet<>();
// Constructors, getters, and setters
}
@Entity public class StudentCourse { @EmbeddedId private StudentCourseId id;
@ManyToOne
@MapsId("studentId")
private Student student;
@ManyToOne
@MapsId("courseId")
private Course course;
private int grade;
// Constructors, getters, and setters
}
@Embeddable public class StudentCourseId implements Serializable {
@Column(name = "student_id")
private Long studentId;
@Column(name = "course_id")
private Long courseId;
// Constructors, getters, and setters
}
在StudentCourse实体中,我们添加了一个额外的列名为'grade”。为了确保在更新StudentCourse实体时额外列的值也得到更新,我们在StudentCourse实体中添加了一个@PreUpdate方法。
@Entity public class StudentCourse { @EmbeddedId private StudentCourseId id;
@ManyToOne
@MapsId("studentId")
private Student student;
@ManyToOne
@MapsId("courseId")
private Course course;
private int grade;
// Constructors, getters, and