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",
public class OrderPersistenceTest extends AbstractTransactionalJUnit4SpringContextTests {

        private OrderDao orderDao;

        private SessionFactory sessionFactory;

	public void testOrderDetailsAreProxied() {
                Session session = sessionFactory.getCurrentSession();
                Order order = new Order("ORDER_ONE");
                OrderDetails orderDetails = new OrderDetails();

                //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

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


It's only fair to share...
Share on Facebook
Tweet about this on Twitter
Share on LinkedIn

1 thought on “Hibernate Persistence Test – Check for Proxy

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

Leave a Reply