[英]Hibernate @OneToMany delete and inser again
我在使用Hibernate 3.6.10.Final时遇到问题。
我有一个使用以下内容映射的OneToMany关系:
public class Master implements Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
Long masterId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "master")
private List<Row> rows = new ArrayList<Attribute>(0);
// Getter and setters and other properties
}
public class Row implements Serializable {
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(
name = "masterId",
column = @Column(name = "masterId", nullable = false)),
// Index is calculated
@AttributeOverride(
name = "index",
column = @Column(name = "index", nullable = false, length = 18))
})
@NotNull
private RowId id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "masterId", nullable = false, insertable = false, updatable = false)
@XmlTransient
private Master master;
// Some other properties, getters and setters
}
我正在实现saveAll REST方法,从请求json序列化的对象是@OneToMany关系的完整表示。
我无法使用休眠自动行为,因为Row.RowId.index是使用旧式算法计算的。
因此,为此,我在create上执行以下操作:
@Transactional
public void createAll(Master master) throws Exception {
// Save in a variable the row list
List<Row> rows = master.getRows();
// Nullify the rows
master.setRows(null);
// Persists the Master using an helper
masterService.persist(master);
for (Row row : rows) {
// the row helper method has the legacy index algorithm
rowService.persist(row);
}
}
而且效果很好,插入操作没有问题。
当我需要在插入之前删除每一行时,问题就出现在更新上。 该代码与insert完全相同,但是调用了deleteAll来执行HQL更新查询。
@Transactional
public void updateAll(Master master) throws Exception {
// Save in a variable the row list
List<Row> rows = master.getRows();
// Nullify the rows
master.setRows(null);
// Persists the Master using an helper
masterService.merge(master);
// Delete Everything before to save
rowService.deleteAll(master);
for (Row row : rows) {
rowService.persist(row);
}
}
这仅在此更新之前没有行的情况下有效。 当有行时,hibernate删除所有内容,插入没有错误的新行,但不会将其持久化到数据库中。
结果是清除所有当前的主行。
有没有一种方法可以清楚地避免此问题? 我不想使用SQL来做这些,我不想将它们混合在一起...
非常感谢Davide。
@OneToMany关系的层叠类型设置为any。 这告诉Hibernate将更改同步到子级。
删除cascadeType,一切正常。
public class Master implements Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
Long masterId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "master")
private List<Row> rows = new ArrayList<Attribute>(0);
// Getter and setters and other properties
}
非常感谢Davide。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.