springboot项目创建笔记18 之《打印mybatis和druid日志》

1、修改application-dev.yml
可以用logback打印druid的Connection、Statement、ResultSet相关日志
修改数据源这段的配置:
1)filters: stat,wall,slf4j
2)添加了slf4j相关的配置

#定义数据源
#参考 https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE
spring:
    datasource:
            druid:
                driver-class-name: com.mysql.cj.jdbc.Driver
                type: com.alibaba.druid.pool.DruidDataSource
                url: jdbc:mysql://localhost:3306/webapp2?serverTimezone=UTC
                username: user2
                password: 654321
                #配置监控统计拦截的filters
                filters: stat,wall,slf4j
                max-active: 20
                initial-size: 1
                max-wait: 60000
                min-idle: 1
                time-between-eviction-runs-millis: 60000
                min-evictable-idle-time-millis: 300000
                test-while-idle: true
                test-on-borrow: false
                test-on-return: false
                pool-prepared-statements: true
                max-open-prepared-statements: 20
                async-init: true
                filter: 
                    slf4j: 
                        enabled: true
                        statement-create-after-log-enabled: false
                        statement-close-after-log-enabled: false
                        result-set-open-after-log-enabled: false
                        result-set-close-after-log-enabled: false

2、logback.xml添加
com.create.entity是DAO的mapper文件所在包路径,不加的话不会打印sql语句

<!-- mybatis打印日志 -->
<logger name="org.apache.ibatis" additivity="false">
	<level value="debug" />
	<appender-ref ref="stdout" />
</logger>
<logger name="org.mybatis" additivity="false">
	<level value="debug" />
	<appender-ref ref="stdout" />
</logger>
<logger name="druid.sql" additivity="false">
	<level value="debug" />
	<appender-ref ref="stdout" />
</logger>
<logger name="com.create.entity" additivity="false">
	<level value="debug" />
	<appender-ref ref="stdout" />
</logger>

3、执行测试案例:

2020-12-16 11:27:29.050 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :Creating a new SqlSession
2020-12-16 11:27:29.059 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8b13d91] was not registered for synchronization because synchronization is not active
2020-12-16 11:27:29.070 [] DEBUG [main] druid.sql.Connection :{conn-10001} pool-connect
2020-12-16 11:27:29.071 [] DEBUG [main] org.mybatis.spring.transaction.SpringManagedTransaction :JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@41aebbb4] will not be managed by Spring
2020-12-16 11:27:29.074 [] DEBUG [main] com.create.entity.TblTeacherInfMapper.selectByPrimaryKey :==>  Preparing: select id, name from tbl_teacher_inf where id = ? 
2020-12-16 11:27:29.208 [] DEBUG [main] druid.sql.Statement :{conn-10001, pstmt-20000} created. select 
     
    id, name
   
    from tbl_teacher_inf
    where id = ?
2020-12-16 11:27:29.217 [] DEBUG [main] com.create.entity.TblTeacherInfMapper.selectByPrimaryKey :==> Parameters: 1(Integer)
2020-12-16 11:27:29.218 [] DEBUG [main] druid.sql.Statement :{conn-10001, pstmt-20000} Parameters : [1]
2020-12-16 11:27:29.218 [] DEBUG [main] druid.sql.Statement :{conn-10001, pstmt-20000} Types : [INTEGER]
2020-12-16 11:27:29.227 [] DEBUG [main] druid.sql.Statement :{conn-10001, pstmt-20000} executed. 9.2053 millis. select 
     
    id, name
   
    from tbl_teacher_inf
    where id = ?
2020-12-16 11:27:29.241 [] DEBUG [main] druid.sql.ResultSet :{conn-10001, pstmt-20000, rs-50000} Result: [1, 刘备]
2020-12-16 11:27:29.242 [] DEBUG [main] com.create.entity.TblTeacherInfMapper.selectByPrimaryKey :<==      Total: 1
2020-12-16 11:27:29.243 [] DEBUG [main] druid.sql.Statement :{conn-10001, pstmt-20000} clearParameters. 
2020-12-16 11:27:29.243 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8b13d91]
2020-12-16 11:27:29.244 [] DEBUG [main] druid.sql.Connection :{conn-10001} pool-recycle
id is: 1
name is: 刘备
2020-12-16 11:27:29.255 [] INFO  [Thread-2] org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor :Shutting down ExecutorService 'applicationTaskExecutor'
2020-12-16 11:27:29.256 [] INFO  [Thread-2] com.alibaba.druid.pool.DruidDataSource :{dataSource-1} closing ...
2020-12-16 11:27:29.263 [] DEBUG [Thread-2] druid.sql.Connection :{conn-10001} closed
2020-12-16 11:27:29.264 [] INFO  [Thread-2] com.alibaba.druid.pool.DruidDataSource :{dataSource-1} closed

显示连接的创建和关闭,详细的sql执行时间

4、sql语句加@Transactional和不加的区别
加@Transactional注解:

2020-12-16 10:07:02.035 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :Creating a new SqlSession
2020-12-16 10:07:02.045 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@119290b9]
2020-12-16 10:07:02.053 [] DEBUG [main] org.mybatis.spring.transaction.SpringManagedTransaction :JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@26f0141] will be managed by Spring
2020-12-16 10:07:02.056 [] DEBUG [main] com.create.entity.TblTeacherInfMapper.selectByPrimaryKey :==>  Preparing: select id, name from tbl_teacher_inf where id = ? 
2020-12-16 10:07:02.077 [] DEBUG [main] com.create.entity.TblTeacherInfMapper.selectByPrimaryKey :==> Parameters: 1(Integer)
2020-12-16 10:07:02.093 [] DEBUG [main] com.create.entity.TblTeacherInfMapper.selectByPrimaryKey :<==      Total: 1
2020-12-16 10:07:02.094 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@119290b9]
id is: 1
name is: 刘备
2020-12-16 10:07:02.098 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@119290b9]
2020-12-16 10:07:02.098 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@119290b9]
2020-12-16 10:07:02.100 [] INFO  [main] org.springframework.test.context.transaction.TransactionContext :Rolled back transaction for test: [DefaultTestContext@30bbcf91 testClass = MybatisTest, testInstance = myboot.MybatisTest@3ca14cf4, testMethod = testMybatis@MybatisTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@1f4f0fcc testClass = MybatisTest, locations = '{}', classes = '{class com.example.myboot.MybootApplication, class com.example.myboot.MybootApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@61d47554, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@4d339552, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@6279cee3, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@36f0f1be], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]]

不加注解:

2020-12-16 10:08:50.052 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :Creating a new SqlSession
2020-12-16 10:08:50.062 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1cd2143b] was not registered for synchronization because synchronization is not active
2020-12-16 10:08:50.205 [] DEBUG [main] org.mybatis.spring.transaction.SpringManagedTransaction :JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@b1b471] will not be managed by Spring
2020-12-16 10:08:50.208 [] DEBUG [main] com.create.entity.TblTeacherInfMapper.selectByPrimaryKey :==>  Preparing: select id, name from tbl_teacher_inf where id = ? 
2020-12-16 10:08:50.232 [] DEBUG [main] com.create.entity.TblTeacherInfMapper.selectByPrimaryKey :==> Parameters: 1(Integer)
2020-12-16 10:08:50.248 [] DEBUG [main] com.create.entity.TblTeacherInfMapper.selectByPrimaryKey :<==      Total: 1
2020-12-16 10:08:50.249 [] DEBUG [main] org.mybatis.spring.SqlSessionUtils :Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1cd2143b]
id is: 1
name is: 刘备

有事务时的执行过程:
1)创建一个新的SqlSession
2)为SqlSession注册事务同步
3)JDBC Connection由spring管理
4)执行sql语句
5)释放事务性SqlSession
6)取消注册SqlSession的事务同步
7)关闭SqlSession
8)由于是测试程序事务回滚

5、Statement和PreparedStatement的区别
Statement对象:用于在已经建立数据库连接的基础上,向数据库发送要执行的sql语句
PreparedStatement:预处理(编译)sql语句并缓存,发送给数据库
ResultSet对象:接收数据库返回结果

参考资料:
https://github.com/alibaba/druid/wiki/Druid%E4%B8%AD%E4%BD%BF%E7%94%A8log4j2%E8%BF%9B%E8%A1%8C%E6%97%A5%E5%BF%97%E8%BE%93%E5%87%BA
https://blog.csdn.net/wantnrun/article/details/94125917

注:最新代码上传至https://github.com/csj50/myboot
 

猜你喜欢

转载自blog.csdn.net/csj50/article/details/111251785