我有以下MySQL表。这里的想法是轨道和课程是主键。轨道中的课程可能取决于“相同轨道”中的另一门课程因此我在(track_id
,depends_on_course_id
)上创建了一个复合FK
CREATE TABLE IF NOT EXISTS `testdb_1`.`track_course` (
`track_id` INT UNSIGNED NOT NULL ,
`course_id` INT UNSIGNED NOT NULL ,
`depends_on_course_id` INT UNSIGNED NULL ,
PRIMARY KEY (`track_id`, `course_id`) ,
INDEX `tc_tbl_dependent_crs_fk_idx` (`track_id` ASC, `depends_on_course_id` ASC) ,
CONSTRAINT `tc_tbl_dependent_crs_fk`
FOREIGN KEY (`track_id` , `depends_on_course_id` )
REFERENCES `testdb_1`.`track_course` (`track_id` , `course_id` ))
以下是由hibernate工具自动生成的类
@Entity
@Table(name = "track_course", catalog = "testdb_1")
public class TrackCourse implements java.io.Serializable {
private TrackCourseId id;
private TrackCourse trackCourse;
private Set<TrackCourse> trackCourses = new HashSet<TrackCourse>(0);
public TrackCourse() {
}
public TrackCourse(TrackCourseId id, TrackCourse trackCourse) {
this.id = id;
this.trackCourse = trackCourse;
}
public TrackCourse(TrackCourseId id, TrackCourse trackCourse,
Set<TrackCourse> trackCourses) {
this.id = id;
this.trackCourse = trackCourse;
this.trackCourses = trackCourses;
}
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "trackId", column = @Column(name = "track_id", nullable = false)),
@AttributeOverride(name = "courseId", column = @Column(name = "course_id", nullable = false)) })
public TrackCourseId getId() {
return this.id;
}
public void setId(TrackCourseId id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
@JoinColumn(name = "track_id", referencedColumnName = "track_id", insertable = false, updatable = false),
@JoinColumn(name = "depends_on_course_id", referencedColumnName = "course_id", insertable = false, updatable = false) })
public TrackCourse getTrackCourse() {
return this.trackCourse;
}
public void setTrackCourse(TrackCourse trackCourse) {
this.trackCourse = trackCourse;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "trackCourse", cascade= CascadeType.ALL)
public Set<TrackCourse> getTrackCourses() {
return this.trackCourses;
}
public void setTrackCourses(Set<TrackCourse> trackCourses) {
this.trackCourses = trackCourses;
}
}
我正在尝试按如下方式写入此表。
TrackCourse tc1 = new TrackCourse(new TrackCourseId(11, 1), null);
TrackCourse tc2 = new TrackCourse(new TrackCourseId(11, 2), tc1);
TrackCourse tc4 = new TrackCourse(new TrackCourseId(11, 4), tc1);
Set<TrackCourse> trackCourses = new HashSet<TrackCourse>();
trackCourses.add(tc2);
trackCourses.add(tc4);
tc1.setTrackCourses(trackCourses);
session.save(tc1); // I expect this statement to create three rows with following values
track_id course_id depends_on_course_id
11, 1, null
11 2 1
11 4 1
但是我在“depends_on_course_id列”中得到了所有null,我想getTrackCourse方法上的映射有问题但我无法弄清楚是什么? 非常感谢任何帮助。
答案 0 :(得分:0)
似乎getTrackCourse()具有空cascadeType,因此默认情况下不会级联任何操作。
顺便说一下。我建议使用生成的键而不是自然键,这会使事情变得更复杂。