Reputation: 53
@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
}
}
I have already successfully mapped Department and Course, in course you can find the department id. I want the same thing to work for Student class, so that I can find Students id in MySQL table @ Course.
I want to add student to a specific course and save it and that does not seem to work either.
Upvotes: 0
Views: 63
Reputation: 53
public void setCourse(Course course) {
courses.add(course);
course.setStudent(this);
}
I just had to set the Student for this course in this method to make the mapping work.
Upvotes: 0
Reputation: 71
The problem is that your @ManyToOne relationship doesn't know how to connect the tables. Please change:
@ManyToOne
Student student;
to:
@ManyToOne
@JoinColumn(name = "student_id")
Student student;
here is a good explanation about @JoinColumns and "mappedBy"
Upvotes: 1
Reputation: 98
Try to enable query generation log, to check what queries exactly are generated. If you will not see any INSERT/UPDATE queries I would assume problems with transactions. Need to make you call transactional.
Upvotes: 0