本文主要是介绍Spring Boot学习之旅:(十六)整合mybatis及日志,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
pom依赖 我们需要引入 数据源 mybatis 和pagehelper
如下
<!-- mybatis支持 --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.0</version></dependency><!--pagehelper --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.1.1</version></dependency><!-- mysql连接池 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.35</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.29</version></dependency>
配置数据源
# 数据库访问配置
# 主数据源,默认的
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/tt
spring.datasource.username=root
spring.datasource.password=123456# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#spring.datasource.useGlobalDataSourceStat=true
进行springboot 与mabatis 的整合
package com.wen.boot.config;import java.util.Properties;import javax.sql.DataSource;import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;import com.github.pagehelper.PageHelper;@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {@AutowiredDataSource dataSource;@Bean(name = "sqlSessionFactory")public SqlSessionFactory sqlSessionFactoryBean() {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setTypeAliasesPackage("com.wen.boot.model");bean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));//添加XML目录ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();try {bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));return bean.getObject();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e);}}@Beanpublic SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {return new SqlSessionTemplate(sqlSessionFactory);}@Bean@Overridepublic PlatformTransactionManager annotationDrivenTransactionManager() {return new DataSourceTransactionManager(dataSource);}@Beanpublic PageHelper pageHelper(){PageHelper pageHelper = new PageHelper(); //添加配置,也可以指定文件路径Properties p = new Properties();p.setProperty("offsetAsPageNum", "true");p.setProperty("rowBoundsWithCount", "true");p.setProperty("reasonable", "true");pageHelper.setProperties(p);return pageHelper;}
}
mapper
@Mapper
public interface IUserDao {public User getUserById(@Param(value="id")int id);
}
service
public interface IUserService {public User getUserById(int id);
}
serviceimpl
@Resourceprivate IUserDao userDao; public User getUserById(int id) {return userDao.getUserById(id);}
mapper xml
<mapper namespace="com.wen.boot.dao.IUserDao"><select id="getUserById" parameterType="Integer" resultType="user">select * from user where id=${id}</select>
</mapper>
controller
@RestController
@RequestMapping("/user")
public class HelloContreller {private Logger logger = LoggerFactory.getLogger(this.getClass());@Autowiredpublic IUserService userService;@GetMapping("/{id}")public User getUser(@PathVariable int id) {return userService.getUserById(id);}
}
启动工程输入
http://localhost:8080/user/1
便可以看到结果
如果看不到mybatis 的日志 执行了那些sql 一旦发生错误很难调试
这里使用log4j2 将日志打印出来
首先更改 pom 移除logging 加入log4j2
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><!-- 想要配置log4j2,就要先去除logging包 --><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency>
编写日志xml
<?xml version="1.0" encoding="utf-8"?>
<configuration><properties><!-- 文件输出格式 --><property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} |-%-5level [%thread] %c [%L] -| %msg%n</property></properties><appenders><Console name="Console" target="system_out"><PatternLayout pattern="${PATTERN}" /></Console></appenders><!--配置mybatis日志--><loggers><logger name="log4j.logger.org.mybatis" level="debug" additivity="false"><appender-ref ref="Console"/></logger><logger name="log4j.logger.java.sql" level="debug" additivity="false"><appender-ref ref="Console"/></logger><logger name="com.wen.boot.dao" level="debug" /><root level="info"><appenderref ref="Console" /></root></loggers></configuration>
引入日志
logging.config=classpath:log4j2.xml
启动工程
输入http://localhost:8080/user/1
可以看到日志的打印
文章地址:http://www.haha174.top/article/details/254914
项目源码:https://github.com/haha174/boot.git
欢迎关注,更多福利
这篇关于Spring Boot学习之旅:(十六)整合mybatis及日志的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!