mybatis-spring整合报错

时间:2021-10-31 05:10:47

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 1.runReflectiveCall(FrameworkMethod.java:44)atorg.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)atorg.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)atorg.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)atorg.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)atorg.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)atorg.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:69)atorg.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48)atorg.junit.runners.ParentRunner 3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner 1.schedule(ParentRunner.java:60)atorg.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)atorg.junit.runners.ParentRunner.access 000(ParentRunner.java:50)
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();会造成重复关闭而报异常,将其删掉即可运行成功。