在我的web應用程序中,我使用的是spring + spring-webmvc + mybatis,並且使用了jndi數據源。spring + mybatis,如何在http請求中共享數據庫連接
我創建了一個mvc控制器來處理用戶的登錄請求。
在控制器中,我需要完成一些與數據庫相關的任務,每個任務將訪問一個服務對象,該對象具有Spring自動連線的mybatis映射器,這將創建一個mybatis sqlsession並使用它並關閉它。
我的問題是,我們可以使所有這些任務共享相同的mybatis sqlsession?
從我的理解,mybatis sqlsession意味着一個jdbc連接涉及。
我不想浪費任何資源。
編輯:
here is the logging message in the real example of my application:
19:26:29.959 [http-8080-3] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
19:26:29.959 [http-8080-3] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [[email protected]] was not registered for synchronization because synchronization is not active
19:26:30.001 [http-8080-3] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [jdbc:h2:tcp://127.0.0.1:6001/cmp, UserName=SA, H2 JDBC Driver] will not be managed by Spring
19:26:30.002 [http-8080-3] DEBUG org.codingfarm.cwe.sys.mappers.UrlRoleMapper.countByExample - ==> Preparing: select count(*) from CMP.PUBLIC.SYS_URL_ROLES WHERE (URL = ?)
19:26:30.002 [http-8080-3] DEBUG org.codingfarm.cwe.sys.mappers.UrlRoleMapper.countByExample - ==> Parameters: index.jsp(String)
19:26:30.008 [http-8080-3] DEBUG org.codingfarm.cwe.sys.mappers.UrlRoleMapper.countByExample - <== Total: 1
19:26:30.008 [http-8080-3] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [[email protected]]
19:26:30.008 [http-8080-3] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
19:26:30.009 [http-8080-3] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [[email protected]] was not registered for synchronization because synchronization is not active
19:26:30.010 [http-8080-3] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [jdbc:h2:tcp://127.0.0.1:6001/cmp, UserName=SA, H2 JDBC Driver] will not be managed by Spring
19:26:30.010 [http-8080-3] DEBUG org.codingfarm.cwe.sys.mappers.UrlRoleMapper.countByExample - ==> Preparing: select count(*) from CMP.PUBLIC.SYS_URL_ROLES WHERE (URL = ? and ROLE_ID in (? , ?))
19:26:30.011 [http-8080-3] DEBUG org.codingfarm.cwe.sys.mappers.UrlRoleMapper.countByExample - ==> Parameters: index.jsp(String), system(String), basic(String)
19:26:30.012 [http-8080-3] DEBUG org.codingfarm.cwe.sys.mappers.UrlRoleMapper.countByExample - <== Total: 1
19:26:30.012 [http-8080-3] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [[email protected]]
編輯: 根據的MyBatis-Spring文檔:
SqlSessionTemplate是MyBatis的彈簧的心臟。它實現了SqlSession,並且是代替任何現有的SqlSession使用的替代品。 SqlSessionTemplate是線程安全的,可以被多個DAO或映射器共享。
那麼如何讓幾個mappers共享一個SqlSessionTemplate?
如果您將SqlSessionTemplate定義爲singleton(這是默認值)bean,那麼您的所有映射器應自動共享該一個實例。剛剛嘗試通過注入各種映射器和是的,他們都有一個參考相同的SqlSessionTemplate。你是否可能將SqlSessionTemplate定義爲Prototype? –