问题报错代码:
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
在做一个SSH联系项目的时候,编写了DAO、SERVICE后,写SERVICE的测试类,代码如下,出现上述问题
public class TestEmpService {
public final Log log = getLog(getClass());
public static ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
EmpService service = (EmpService) ctx.getBean("empService");
@Test
public void testGetEntitySerializable() {
log.info("按id查询employee测试");
<span style="background-color: rgb(255, 0, 0);">Employee e = service.getEntity(1);</span>
assertTrue(e != null);
if (null != e) {
log.info(e.getNickname());
}
}
根据控制台错误提示,指向的代码为DAO层:
public class BaseDaoImpl<T> implements BaseDao<T> {
/**
* DAO组件进行持久化操作底层依赖的SessionFactory组件,由spring依赖注入
*/
@Autowired
private SessionFactory sessionFactory;
private Logger logger = Logger.getLogger(getClass());
@SuppressWarnings("unchecked")
@Override
public T get(Class<T> entityClazz, Serializable id) {
logger.info("查询ID = " + id + " 的 " + entityClazz);
return (T) <span style="background-color: rgb(255, 0, 0);">getSessionFactory().getCurrentSession().get(entityClazz, id);</span>
}
下面省略...
大概说说用getCurrentSession时候出现这个问题。
之前这个项目是自己编写了ThreadLocal管理session,CRUD操作的时候用的是session.openSession,每次操作都要close一下。
大概不明白其中的问题,总之先查了两者的区别:
http://wenku.baidu.com/link?url=OimQ-55pxZvbAF6EB24aNP4XEJxzfPQEE1Q8gixNlbzPS8coXpuNoekV08ij4aIkQU3P3WC0v0FteFXqgYQuyGHD9lzigQGJuhObHIQ9fH3
原来涉及到事务,总之也不懂
又参考了:
http://blog.csdn.net/liushuijinger/article/details/17364413
http://blog.csdn.net/yinjian520/article/details/8666695
虽然最后也没整明白...
总之先在@service前添加了@Transactional试了试,还是不行
报了新的错误:
java.lang.ClassCastException: com.sun.proxy.$Proxy20 cannot be cast to com.crm.service.impl.EmpService
估计是proxy这涉及什么代理之类的,总之继续百度
继续参考:
http://forum.spring.io/forum/spring-projects/aop/100556-proxy25-cannot-be-cast-to-my-class
在spring的配置文件中,下面这句一直没用过,貌似是管理事务的,按照文章的说法,将其进行了修改
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:annotation-driven transaction-manager="transactionManager" <span style="background-color: rgb(51, 51, 255);">proxy-target-class="true"</span>/>
添加了蓝色部分代码,通过测试。
至于为什么,暂时还不清楚,先记录在这,下面是测试结果:
19:05:28,128 INFO TestEmpService:23 - 按id查询employee测试
19:05:28,284 INFO EmpDao:27 - 查询ID = 1 的 class com.crm.entity.Employee
19:05:28,452 INFO TestEmpService:27 - Jack