为什么hibernate会从关联表中删除数据?

时间:2013-04-09 19:24:00

标签: java hibernate annotations mapping

我的程序中有以下关系:

@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);
}

1 个答案:

答案 0 :(得分:0)

好像我刚刚发现了这个问题。现在无法在我的旧项目中查看它,但它与this hibernate bug相关的问题非常相似。