Thursday, April 29, 2010

JUnit Hibernate Lazy initialization

To configure your JUnit testcases for testing data access through Hibernate with entity mappings using lazy initialization requires minor changes to the setUp() and tearDown() methods as follows:


    /**
     * The application context used in this test case.
     */
    protected ApplicationContext ctx;
    protected StrainDao dao;
    // keep reference to session factory to handle lazy-initialization
    protected SessionFactory sessionFactory;
    protected Session session;
    
    public PhenomeBankTestCase(final String name) {
        super(name);

        // Override the default definition for dataSource
        /*
        final String[] files = {                    
            "file:C:/workspace/mouse/src/main/webapp/WEB-INF/applicationContext-hibernate.xml",
            "classpath:applicationContextDataSource.xml",
            "file:C:/workspace/mouse/src/main/webapp/WEB-INF/phenomeBank-service.xml",             
        };*/
        
        final String[] files = {                    
                "file:./src/main/webapp/WEB-INF/applicationContext-hibernate.xml",
                "classpath:applicationContextDataSource.xml",
                "file:./src/main/webapp/WEB-INF/phenomeBank-service.xml",             
            };        

        ctx = new ClassPathXmlApplicationContext(files);
        sessionFactory = (SessionFactory)ctx.getBean(BEAN_ID_SESSION_FACTORY);
    }
    
    /**
     * Sets up the test fixture.
     */
    @Override
    public void setUp() {
        dao = (StrainDao) ctx.getBean(BEAN_ID_STRAIN_DAO);         

        session = SessionFactoryUtils.getSession(this.sessionFactory, true);
        TransactionSynchronizationManager.bindResource(this.sessionFactory, new SessionHolder(session));        
    }

    @Override
    protected void tearDown() throws Exception {
        TransactionSynchronizationManager.unbindResource(this.sessionFactory);
        SessionFactoryUtils.releaseSession(this.session, this.sessionFactory);
    }



Reference: http://note19.com/2007/08/26/lazy-initialization-with-hibernate-and-spring/

No comments:

Post a Comment