jpa和mysqlMap实体

1bqhqjot  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(308)
@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

    }
}

我已经成功地Map了部门和课程,当然你可以找到部门id。我想要同样的东西为学生类工作,这样我就可以在mysql表@course中找到学生id。
我想将学生添加到一个特定的课程并保存它,这似乎也不起作用。

tpxzln5u

tpxzln5u1#

问题是@manytoone关系不知道如何连接表。请更改:

@ManyToOne
Student student;

收件人:

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

下面是关于@joincolumns和“mappedby”的一个很好的解释

dm7nw8vv

dm7nw8vv2#

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

我只需要给这门课的学生设置这个方法,就可以使绘图工作正常。

ttcibm8c

ttcibm8c3#

尝试启用查询生成日志,以检查究竟生成了哪些查询。如果您看不到任何插入/更新查询,我将假设事务有问题。需要让你打电话给我。

相关问题