我使用Spring的HibernateDAOSupport类来处理我的DAO。 我的问题是,当我使用getHibernateSupport()。save(order)时,数据库中已经存在订单,它只是更新数据库行而不是抛出某种异常。
我的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()只是因为主键已经存在而抛出异常而更新数据库行。
答案 0 :(得分:1)
第二个save
被加入,因为您正在保存已保存的同一个CustomerOrder
实例(即持久对象)。如果您尝试保存具有相同ID的不同实例(即瞬态对象),则会出现异常。