@Entity
@Table(name = "COURSE")
public class Course {
@Id
@GeneratedValue
private Long id;
@Column(name = "course_name")
private String courseName;
@ManyToOne
Department department;
@ManyToOne
Student student;
protected Course() {}
public Course(String name, Department department) {
this.department = department;
courseName = name;
}
}
@Entity
@Table(name = "STUDENT")
public class Student {
@Id
@GeneratedValue
private Long id;
@Column(name = "locker_id")
private int lockerId;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "student",
cascade = CascadeType.ALL)
List<Course> courses = new ArrayList<>();
@Embedded
private Person attendee;
protected Student(){}
public Student(Person person, int lockerId) {
attendee = person;
this.lockerId = lockerId;
courses = new ArrayList<>();
}
public void setCourse(Course course) {
courses.add(course);
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
public List<Course> getCourses() {
return courses;
}
}
@SpringBootApplication
public class UniversityApplication implements CommandLineRunner {
@Autowired
CourseRepository courseRepository;
@Autowired
DepartmentRepository departmentRepository;
@Autowired
StudentRepository studentRepository;
public static void main(String[] args) {
SpringApplication.run(UniversityApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
//Students
Student one = studentRepository.save(new Student(new Person("jane", "doe"), 20));
//Courses
Course english101 = courseRepository.save(new Course("English 101", humanities));
Course english202 = courseRepository.save(new Course("English 202", humanities));
//This does not add student to a course, why?
//Ask
one.setCourse(english101);
studentRepository.save(one);
//How to map course with student and then to find students in a particular course
}
}我已经成功地映射了部门和课程,当然您可以找到部门标识。我希望同样的东西在学生班工作,这样我就可以在MySQL table @ Course中找到学生id。
我想增加学生到一个特定的课程,并保存它,这似乎也不起作用。
发布于 2018-05-28 09:53:10
public void setCourse(Course course) {
courses.add(course);
course.setStudent(this);
}我只需要用这种方法来设置这个课程的学生,才能使映射工作。
发布于 2018-04-23 12:24:24
问题是您的@ManyToOne关系不知道如何连接这些表。请更改:
@ManyToOne
Student student;至:
@ManyToOne
@JoinColumn(name = "student_id")
Student student;下面是关于@JoinColumns and "mappedBy"的一个很好的解释
发布于 2018-04-23 12:20:53
尝试启用查询生成日志,以检查确切生成了哪些查询。如果您没有看到任何INSERT/UPDATE查询,我将假设事务存在问题。需要让你打电话给事务性。
https://stackoverflow.com/questions/49980317
复制相似问题