mybatis-spring整合报错
java.lang.UnsupportedOperationException: Manual close is not allowed over a Spring managed SqlSession
at org.mybatis.spring.SqlSessionTemplate.close(SqlSessionTemplate.java:310)
at com.demo.dao.UserDaoImpl.findUserById(UserDaoImpl.java:16)
at com.demo.test.UserDaoTest.findUserById(UserDaoTest.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod
at org.junit.runners.ParentRunner
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
部分代码
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public User findUserById(Integer id) {
SqlSession openSession = this.getSqlSession();
User user = openSession.selectOne("user.findUserById", id);
openSession.close();
return user;
}
SqlSessionTemplate是一个代理类,内部会为每次请求创建线程安全的sqlsession,并与Spring进行集成.在方法调用完毕以后会自动关闭的。所以使用SqlSessionTemplate时不可以手动关闭。代码中openSession.close();会造成重复关闭而报异常,将其删掉即可运行成功。