我正在尝试使用休眠进行一对多映射以将一些信息插入数据库,但每次数据在表中更新而不是插入新行
我有 2 个实体:ReportMaster 和 Reportdetail。其中许多 Reportdetail 数据包含 ID,该 ID 是映射到报告主主键列 ID 的外键
@Entity
@Table(name = "ReportMaster")
public class ReportMaster implements Serializable {
private Integer repId;
private Set<ReportDetail> reportDetails = new HashSet<ReportDetail>();
@Id
@GeneratedValue
@Column(name = "RepId", unique = true, nullable = false)
public Integer getRepId() {
return this.repId;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "reportMaster")
public Set<ReportDetail> getReportDetails() {
return this.reportDetails;
}
第二个实体是:
@Entity
@Table(name = "ReportDetail")
public class ReportDetail implements Serializable {
private String repColumn;
private String colData;
//.......corresponding getters and setters
private ReportMaster reportMaster;
@ManyToOne(targetEntity = ReportMaster.class)
@JoinColumn(name = "RepId")
public ReportMaster getReportMaster() {
return this.reportMaster;
}
我想在 reportdetails 表中插入一个新行,但它正在更新:
ReportMaster report=new ReportMaster(req.getReportName(), req.getCid(), req.getReportDesc(), new Date());
report.addDetail(new ReportDetail(repcol,desc);
getTemplate().save(obj);
生成的 HQL 为:
org.hibernate.SQL - insert into ReportMaster (CreateDate, CustomerID, RepDesc, ReportName) values (?, ?, ?, ?)
org.hibernate.SQL - update ReportDetail set RepId=? where ColData=? and RepColumn=?
2013-02-16 10:13:34,109[http-6060-1] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.jdbc.BatchedTooManyRowsAffectedException: Batch update returned unexpected row count from update [0]; actual row count: 2; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:71)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:24)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2403)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2307)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2607)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:92)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:234)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:142)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)