0
我使用Spring的HibernateDAOSupport類來處理我的DAO。 我的問題是,當我使用getHibernateSupport()。save(order)命令時,數據庫中已經存在命令,它只是更新數據庫行而不是拋出某種異常。HibernateTemplate嘗試插入重複鍵行時保存不拋出異常
我的Hibernate的hbm.xml文件是:
<hibernate-mapping>
<class name="com.shopping.db.CustomerOrder" table="CUSTOMERORDER" schema="PUBLIC">
<id name="orderID" type="long">
<column name="ORDERID" length="50" />
</id>
<many-to-one name="customer" class="com.shopping.db.Customer" fetch="select">
<column name="USERNAME" length="50" not-null="true" />
</many-to-one>
<property name="status" type="string">
<column name="STATUS" length="50" not-null="true" />
</property>
<property name="totalCost" type="float">
<column name="TOTALCOST" precision="0" scale="0" not-null="true" />
</property>
<property name="orderDate" type="java.sql.Date">
<column name="ORDERDATE" not-null="true" />
</property>
</class>
</hibernate-mapping>
我的DAO代碼:
public void createDBOrder(CustomerOrder order, List<OrderItem> orderItems)
{
getHibernateTemplate().save(order);
for (OrderItem item : orderItems)
{
getHibernateTemplate().save(item);
}
getHibernateTemplate().flush();
}
我的測試方法如下:
@Test
public void testCreateDBOrder()
{
int ordersCount = countRowsInTable("CUSTOMERORDER");
int orderItemsCount = countRowsInTable("ORDERITEM");
// Check for row count before insertion.
assertEquals(1, ordersCount);
assertEquals(1, orderItemsCount);
CustomerOrder order = new CustomerOrder(3, dataAccessObject
.getCustomerByName("Oussama"), "PENDING", 200, new Date(new Long(
"61191781200000")));
OrderItem item = new OrderItem(333, dataAccessObject.getProductByID("Apple iPhone"), order, 3);
OrderItem item2 = new OrderItem(444, dataAccessObject.getProductByID("DV2000"), order, 2);
List<OrderItem> items = new ArrayList<OrderItem>();
items.add(item);
items.add(item2);
dataAccessObject.createDBOrder(order, items);
ordersCount = countRowsInTable("CUSTOMERORDER");
orderItemsCount = countRowsInTable("ORDERITEM");
// Check for row count after insertion.
assertEquals(2, ordersCount);
assertEquals(3, orderItemsCount);
assertEquals(3, dataAccessObject.getOrderByID(3).getOrderID());
assertEquals(2, dataAccessObject.getOrderItemByOrderID(3).size());
order.setStatus("SHIPPED");
// Check for creating a order with the same ID.
dataAccessObject.createDBOrder(order, items);
assertEquals("SHIPPED", dataAccessObject.getOrderByID(3).getStatus());
ordersCount = countRowsInTable("CUSTOMERORDER");
// Check for row count after insertion.
//assertEquals(3, ordersCount);
}
爲什麼getHibernateTemplate() .save()只是更新數據庫行,而不是由於主鍵已經存在引發異常。
謝謝。這就說得通了。我使用了不同的實例,並且出現異常。有趣!!! – Sammy 2010-07-06 11:46:00