我有一个名为“Document”的对象,它与“DocumentPersonCc”具有一对多的关系。我试图在我的代码中更改一个或多个这些集合,但Hibernate并没有在我期望的时候调用更新查询。当我更改其中一个常规字段(如文档主题)时,它会调用更新查询,但即使这样,它也不会保留数据库中的任何一对多更改。为了让它发挥作用我需要改变什么?
DocumentPersonCc的Getter和setter:
@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的Document getter和setter:
@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;
}
答案 0 :(得分:3)
试试这个 -
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "document")
@LazyCollection(LazyCollectionOption.EXTRA)
@Sort(type = SortType.NATURAL, comparator = DocumentPersonCc.class)
public SortedSet<DocumentPersonCc> getDocumentPersonCcs() {
return this.documentPersonCcs;
}
使用级联更新子映射
答案 1 :(得分:1)
在Document实体类中使用cascade。 `
@OneToMany(fetch = FetchType.LAZY, mappedBy = "document")
@LazyCollection(LazyCollectionOption.EXTRA)
@Sort(type = SortType.NATURAL, comparator = DocumentPersonCc.class)
@Cascade({CascadeType.SAVE_UPDATE})
public SortedSet<DocumentPersonCc> getDocumentPersonCcs() {
return this.documentPersonCcs;
}
`然后在保存或更新文档实体时保存或更新集合。
答案 2 :(得分:0)
在Document.java中添加一个方法
public void addDocumentPersonCc(DocumentPersonCc documentPersonCc) {
documentPersonCc.setDocument(this);
documentPersonCcs.add(documentPersonCc);
}
现在将updateCcs方法更改为
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());
SortedSet<DocumentPersonCc> documentPersonCcsList = document.getDocumentPersonCcs();
//Iterate this documentPersonCcsList
{
// add oldD.addDocumentPersonCc(Value from Iterator);
}
session.update(oldD);
session.getTransaction().commit();
document = this.returnDocument(document.getId());
Hibernate.initialize(document.getDocumentPersonCcs());
return document;
}