[英]Hibernate Insert is trying to update identity column
我是Hibernate的新手,嘗試在數據庫中保留對象時遇到一些問題。
@Entity
@Table(name="order")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long number;
@Column(name="date")
private Timestamp date;
@Column(name="obs")
private String obss;
@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
@JoinColumn(name="id", referencedColumnName="number")
private List <OrderDetail> orderDetail;
(...)
和OrderDetail類
@Entity
@Table(name="orderDetail")
public class OrderDetail implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(name="orderType")
private Long orderType;
(...)
當我嘗試將對象保存到數據庫時,出現以下錯誤:
Hibernate:
insert
into
order
(date, obs, rejectObs, pid, destiny, stateId, userId, version)
values
(?, ?, ?, ?, ?, ?, ?, ?)
Hibernate:
insert
into
OrderDetail
(boxId, date, digitalid, documentId, rejectObs, obs, orderId, stateId, orderType)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?,)
Hibernate:
update
OrderDetail
set
id=?
where
id=?
16/09/2014 11:50:03 org.hibernate.util.JDBCExceptionReporter logExceptions
WARNING: SQL Error: 8102, SQLState: S1000
16/09/2014 11:50:03 org.hibernate.util.JDBCExceptionReporter logExceptions
ERROR: Cannot update identity column 'id'.
16/09/2014 11:50:03 org.hibernate.event.def.AbstractFlushingEventListener performExecutions
GRAVE: Could not synchronize database state with session
org.hibernate.exception.GenericJDBCException: could not insert collection: [com.sa.ra.entities.Order.orderDetail#4252]
我不知道為什么Hibernate試圖更新orderDetail表。 有人知道發生了什么嗎? 即時通訊使用SQL Server 2008和休眠3.5.0
有一個概念錯誤。
您要讓hibernate引用兩個實體,並將它們的ID用作彼此的主鍵和外鍵。 錯了
將兩個實體建立一對多關系的正確方法是在“許多”側添加一個外鍵,該外鍵必須引用“一個”類的主鍵。 這是數據庫問題,不僅是休眠限制。
您可以在此處閱讀有關Hibernate Collections的更多信息。
根據上述文檔,您必須按如下方式修改代碼:
“一個”方面
@Entity
@Table(name="order")
public class Order implements Serializable {
[...]
@OneToMany(targetEntity = OrderDetail.class, cascade = CascadeType.ALL, mappedBy = "order", fetch = FetchType.LAZY)
private List <OrderDetail> orderDetail;
[...]
}
然后,“許多”方面:
@Entity
@Table(name="orderDetail")
public class OrderDetail implements Serializable {
[...]
@ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
@JoinColumn(name = "order_id", nullable = false)
private Order order;
[...]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.