package org.summerfragrance; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.summerfragrance.support.hibernate3.HibernateLazyResolver; public class BaseTestCase extends TestCase { protected final Log log = LogFactory.getLog(getClass(););; protected final static ApplicationContext ctx; protected HibernateLazyResolver hibernateLazyResolver; static { String[] paths = { "/conf/applicationContext-dataSource.xml", "/org/summerfragrance/vfs/applicationContext-vfs.xml", "/org/summerfragrance/security/dao/hibernate/applicationContext-hibernate.xml" // "/org/summerfragrance/security/dao/jdbc/applicationContext-jdbc.xml" }; ctx = new ClassPathXmlApplicationContext(paths);; } protected void setUp(); throws Exception { super.setUp();; hibernateLazyResolver = (HibernateLazyResolver); ctx .getBean("hibernateLazyResolver");; hibernateLazyResolver.openSession();; } protected void tearDown(); throws Exception { super.tearDown();; hibernateLazyResolver.releaseSession();; hibernateLazyResolver = null; } } |
这样就可以在 Service 和 TestCase 中使用 Lazy Load 了, 目前已经测试通过
这几天看 JavaEye 上关于 OpenSessionInView 的讨论, 感觉这个问题比较常见
Java代码
1.在代码中调用 openSession();, 然后不予处理, 这就是 ajoo 说的第一种不擦屁股就直接走人的做法, 这样可能导致两种错误;
a. org.springframework.orm.hibernate3.HibernateSystemException: Illegal attempt to associate a collection with two open sessions
b. 数据库连接不关闭
正确的做法是用 HibernateCallBack 或者参照 HibernateTemplate 对 session 进行处理