Hibernate Persistence Test – Check for Proxy

Recently we ran into a performance problem, the root cause of which is described in One-to-one Hibernate mapping not proxied if optional.

As an after thought I wondered if a unit test approach could help ensure your Hibernate mapping is actually working the way you intend.

Here’s a test that checks if a relationship is proxied (would have come in handy in our one-to-one gaff.
(NOTE: We’re using the Spring TestContext Framework for this test)

@ContextConfiguration(locations = {"classpath:dataSource.xml",
	"classpath:applicationContext.xml"})
public class OrderPersistenceTest extends AbstractTransactionalJUnit4SpringContextTests {

        @Autowired
        private OrderDao orderDao;

        @Autowired
        private SessionFactory sessionFactory;

	@Test
        @Transactional
        @Rollback(true)
	public void testOrderDetailsAreProxied() {
                //Setup
                Session session = sessionFactory.getCurrentSession();
                Order order = new Order("ORDER_ONE");
                OrderDetails orderDetails = new OrderDetails();
                orderDetails.setRushDelivery(true);
                order.setOrderDetails(orderDetails);

		orderDao.save(order);
                //sync with DB transaction
		session.flush(); // Might not be necessary depending on Transaction Propagation

		Long orderId= (Long) order.getId();

                // Clear the session or Order and OrderDetails so Hibernate will query database for relationship
		getSessionFactory().getCurrentSession().clear();

                //SUT (System Under Test)
		order= (Order) orderDao().get(Order.class, orderId);

		Assert.assertFalse(Hibernate.isInitialized(order.getOrderDetails));
	}
}

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

One thought on “Hibernate Persistence Test – Check for Proxy

  1. Pingback: Spring TestContext Framework | i-Proving –

Leave a Reply