我的程序中有以下关系:
@Entity
@Table(name = "student")
public class Student extends Person {
private Map<Document, DocumentInfo> documents =
new HashMap<Document, DocumentInfo>();
...
@OneToMany
@JoinTable(name = "student_documents",
joinColumns = @JoinColumn(name = "student"),
inverseJoinColumns = @JoinColumn(name = "document_info"))
@MapKeyJoinColumn(name = "document")
public Map<Document, DocumentInfo> getDocuments() {
return documents;
}
...
}
当我用他的文件保存学生时,信息似乎都很好..
当我从数据库中读取他时,一切看起来都很好,但是当我再次尝试读取它时,我有NullPointerException。我做了一些研究,发现在第一次调用student.getDocuments()
时,hibernate删除了表student_documents
中的记录:
Hibernate: select document0_.id as id2_0_, document0_.title as title2_0_ from document document0_ where document0_.id=?
Hibernate: select document0_.id as id2_0_, document0_.title as title2_0_ from document document0_ where document0_.id=?
Hibernate: delete from student_documents where student=?
我做错了什么? 感谢
我的测试代码如下:
Student student = new Student();
student.setFirstName("123");
studentService.add(student);
Student student2 = studentService.read(student.getId());
assertFalse(student2.getDocuments().size() == 0); // here it all occurs
服务方式:
public Student add(Student student) {
for (Document document : documentRepository.findAll()) {
DocumentInfo documentInfo = new DocumentInfo(false, "");
documentInfoRepository.save(documentInfo);
student.getDocuments().put(document, documentInfo);
}
return studentRepository.save(student);
}