Hello,
I m using Spring's HibernateDAOSupport class to handle my DAO. my problem is that when I use getHibernateSupport().save(order) when order already exist in the database, it just update the database row instead of throwing some kind of Exception.
my Hibernate hbm.xml file is :
<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>
my DAO code is :
public void createDBOrder(CustomerOrder order, List<OrderItem> orderItems)
{
getHibernateTemplate().save(order);
for (OrderItem item : orderItems)
{
getHibernateTemplate().save(item);
}
getHibernateTemplate().flush();
}
my test method is as follow:
@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);
}
Why is getHibernateTemplate().save() is just updating the database row instead if throwing an exception because of primary key already exists.