Spring Boot学习之旅:(十六)整合mybatis及日志

2024-08-22 22:38

本文主要是介绍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及日志的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1097598

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

MyBatis常用XML语法详解

《MyBatis常用XML语法详解》文章介绍了MyBatis常用XML语法,包括结果映射、查询语句、插入语句、更新语句、删除语句、动态SQL标签以及ehcache.xml文件的使用,感兴趣的朋友跟随小... 目录1、定义结果映射2、查询语句3、插入语句4、更新语句5、删除语句6、动态 SQL 标签7、ehc

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

MyBatis延迟加载与多级缓存全解析

《MyBatis延迟加载与多级缓存全解析》文章介绍MyBatis的延迟加载与多级缓存机制,延迟加载按需加载关联数据提升性能,一级缓存会话级默认开启,二级缓存工厂级支持跨会话共享,增删改操作会清空对应缓... 目录MyBATis延迟加载策略一对多示例一对多示例MyBatis框架的缓存一级缓存二级缓存MyBat