gpt4 book ai didi

java - JPA 和 MySQL 映射实体

转载 作者:行者123 更新时间:2023-11-29 10:17:01 25 4
gpt4 key购买 nike

@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

}
}

我已经成功映射了部门和类(class),当然你可以找到部门id。我希望同样的事情也适用于 Student 类,这样我就可以在 MySQL 表 @ Course 中找到 Students id。

我想将学生添加到特定类(class)并保存它,但这似乎也不起作用。

最佳答案

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

 @ManyToOne
Student student;

至:

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

这里有一个关于 @JoinColumns and "mappedBy" 的很好的解释

关于java - JPA 和 MySQL 映射实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49980317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com