我有一个名为“Document”的对象,它与“DocumentPersonCc”具有一对多的关系。我试图在我的代码中更改这些集合中的一个或多个,但 Hibernate 并没有在我期望的时候调用更新查询。当我更改其中一个常规字段(如文档主题)时,它确实会调用更新查询,但即便如此,它也不会保留数据库中的任何一对多更改。为了让它工作,我需要改变什么?
DocumentPersonCc 的获取器和设置器:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "document")
@LazyCollection(LazyCollectionOption.EXTRA)
@Sort(type = SortType.NATURAL, comparator = DocumentPersonCc.class)
public SortedSet<DocumentPersonCc> getDocumentPersonCcs() {
return this.documentPersonCcs;
}
public void setDocumentPersonCcs(
SortedSet<DocumentPersonCc> documentPersonCcs) {
this.documentPersonCcs = documentPersonCcs;
}
更新代码:
public Document updateCcs(Document document) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Document oldD = (Document) session.load(Document.class, document.getId());
Hibernate.initialize(oldD.getDocumentPersonCcs());
oldD.setDocumentPersonCcs(document.getDocumentPersonCcs());
session.update(oldD);
session.getTransaction().commit();
document = this.returnDocument(document.getId());
Hibernate.initialize(document.getDocumentPersonCcs());
return document;
}
DocumentPersonCc 的文档获取器和设置器:
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "DocumentsId", nullable = false, insertable = false, updatable = false)
protected Document getDocument() {
return this.document;
}
public void setDocument(Document document) {
this.document = document;
}