JPA和MySQL映射引人入胜

时间:2018-04-23 11:44:21

标签: java mysql jpa

@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

    }
}

我已经成功映射了部门和课程,当然你可以找到部门ID。我希望同样的东西可以用于Student课程,这样我就可以在MySQL table @ Course中找到Students id。

我想将学生添加到特定课程并保存,但这似乎也不起作用。

3 个答案:

答案 0 :(得分:1)

问题是你的@ManyToOne关系不知道如何连接表。请改变:

 @ManyToOne
Student student;

为:

@ManyToOne
@JoinColumn(name = "student_id")
Student student;

这是关于@JoinColumns and "mappedBy"

的一个很好的解释

答案 1 :(得分:0)

尝试启用查询生成日志,以检查确切生成的查询。如果您没有看到任何INSERT / UPDATE查询,我会假设事务有问题。需要让你打电话给交易。

答案 2 :(得分:0)

   public void setCourse(Course course) {
        courses.add(course);
        course.setStudent(this);
    }

我只需要在此方法中为此课程设置学生,以使映射工作。