我有两个表,orders 和 order_items。它们之间的关系是一对多的。Order_items.fk_orders 是外键。Orders.ID 是主键。
我先保存订单再保存order_items,但是order_items.fk_orders和orders.ID不同,order_items.fk_orders的值很长(比如'3213148',但正常值是'425618'),才出现问题有时。
Orders.hbm.xml as below:
....
<id name="id" column="ID" type="java.lang.Long">
<generator class="native">
</generator>
</id>
<set name="orderProduct" lazy="false" cascade="all"
sort="unsorted">
<key column="FK_ORDERS"></key>
<one-to-many
class="com.arvato.ecommerce.model.base.OrderItems"/>
</set>
....
OrderItem.hbm.xml as below:
....
<id name="id" column="ID" type="java.lang.Long">
<generator class="native">
</generator>
</id>
<many-to-one name="orders"
class="com.arvato.ecommerce.model.base.Orders" cascade="none"
outer-join="auto" update="true" insert="true" lazy="false"
column="FK_ORDERS"/>
....
The code as below:
//save order
Orders orders = new Orders();
....
....
orders.setOrderItems(null);//(I think it is strange I don't know why set the null value to OrderItems?)
session = getSession();
session.save(object);
session.flush()
//save order items
....
Collection orderItems = orders.getOrderItems();
if (orderItems != null) {
OrderItem orderItem;
for (Iterator itemIterator = orderItems.iterator(); itemIterator.hasNext(); orderdao.insertOrderProduct(orderItem)) {
orderItem = (OrderItem) itemIterator.next();
orderItem.setOrders(orders);
}
}
....
public int insertOrderProduct(OrderItem orderItem)
throws DaoException {
Session session =null;
try {
session = getSession();
session.save(orderItem);
session.flush();
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}