gpt4 book ai didi

java - Hibernate Insert 正在尝试更新标识列

转载 作者:太空宇宙 更新时间:2023-11-04 14:33:24 24 4
gpt4 key购买 nike

我是 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 和 hibernate 3.5.0

最佳答案

存在概念错误。

您要求 hibernate 使用两个实体的 id 作为彼此的主键和外键来引用两个实体。这是错误的。

将两个实体置于一对多关系中的正确方法是在“多”端添加一个外键,该外键必须引用“一”类的主键。这是数据库问题,而不仅仅是 hibernate 限制。

您可以阅读有关 Hibernate Collections here 的更多信息

根据上述文档,您必须按如下方式修改代码:

“一”面

@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;
[...]
}

关于java - Hibernate Insert 正在尝试更新标识列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25872510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com