Hibernate Insert正在尝试更新标识列

时间:2014-09-16 15:15:33

标签: java sql hibernate

我是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;

(...)

当我尝试将对象保存到DB中时,我得到以下错误:

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

1 个答案:

答案 0 :(得分:0)

出现了一个概念错误。

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

将两个实体放在一对多关系中的正确方法是在&#34; many&#34;中添加一个外键。一方面,必须引用&#34;一个&#34;的主键。类。这是一个数据库问题,它不仅仅是一种休眠限制。

您可以阅读有关Hibernate Collections here

的更多信息

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

&#34; one&#34;侧

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

然后,&#34;很多&#34;侧:

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