0

我有两个表,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;
        }
    }
4

1 回答 1

0

您的映射似乎是正确的,这就是您使用它的方式是错误的。既然你使用cascade="all"了,所有OrderItems列在一个实例中的Orders都会在你保存Orders实例的时候自动持久化!

下面的代码应该足够了:

Orders orders = new Orders();
orders.addItem(new OrderItem());
...

session = getSession();
session.save(object);
session.flush()

addItem 方法如下所示:

public void addItem(OrderItem item) {
    if (items == null) {
        items = new ArrayList<OrderItem>();
    }
    item.setOrders(this);
    items.add(item);
}
于 2013-03-18T09:44:36.803 回答