我有一个具有[[大学和学生的简单数据库(请参见下面的实体)
University.javaimport lombok.Getter;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Getter
@Setter
@Table(name = "university")
public class University {
@Id
@GeneratedValue
@Column(name = "university_id")
private long id;
@Column(name = "university_name")
private String name;
public University() {
}
public University(String name) {
this.name = name;
}
}
Student.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Getter
@Setter
@Table(name = "student")
public class Student {
@Id
@GeneratedValue
@Column(name = "student_id")
private long id;
@Column(name = "student_name")
private String studentName;
@JoinColumn(name="university_name")
private String studentUniversityName;
@ManyToOne
private University university;
public Student() {
}
public Student(String name, String studentUniversityName) {
this.name = name;
this.studentUniversityName = studentUniversityName;
}
}
我的实体应在university_name
列上加入。我编写了以下单元测试来验证此行为。
@Test void test1() { final String UNIVERSITY_NAME = "U of A"; universityRepository.save(new University(UNIVERSITY_NAME)); studentRepository.save(new Student("Joe", UNIVERSITY_NAME)); Student joe = studentRepository.findAll().get(0); assertNotNull(joe.getUniversity()); // <------ FAILING }
assertNotNull(joe.getUniversity())
语句失败,这似乎表明表未联接。对我来说,奇怪的是,下一个测试通过了(当我明确地将大学设置为Joe时。(数据库的内容在两种方法中都是相同的,但是此测试的findAll()
似乎正确触发了连接)
@Test void test2() { final String UNIVERSITY_NAME = "U of A"; University uni = new University(UNIVERSITY_NAME); universityRepository.save(uni); Student joe1 = new Student("Joe", UNIVERSITY_NAME); joe1.setUniversity(uni); studentRepository.save(joe1); Student student = studentRepository.findAll().get(0); assertNotNull(student.getUniversity()); }
我不想在救他之前将大学设置为Joe(就像在第二个测试中一样),因为有时我想在代码中的不同时间保存学生和大学。我希望能够用空大学来保存Joe并在对findAll()
的调用中填充字段有人可以帮我修改我的实体,以便通过第一项测试吗?
public class Student {
@Id
@GeneratedValue
@Column(name = "student_id")
private long id;
@Column(name = "student_name")
private String studentName;
@ManyToOne
@JoinColumn(name="university_name")
private University university;
public Student() {
}
public Student(String name, String studentUniversityName) {
this.name = name;
this.studentUniversityName = studentUniversityName;
}
}
public class University {
@Id
@GeneratedValue
@Column(name = "university_id")
private long id;
@Column(name = "university_name")
private String name;
@OneToMany(mappedBy="university")
private List<Student> students= new ArrayList<Student>();
public University() {
}
public University(String name) {
this.name = name;
}
}