我是靠谱客的博主 平常板凳,最近开发中收集的这篇文章主要介绍druid mysql配置详解_springboot+druid+mybatis-Plus 配置详解,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

网上找了很多关于springboot+druid+mybatis-Plus的配置,遇见的很多问题 也没找到好的解决方案。折腾了好几天终于自己配置通过了。

springboot的pom文件

1

2 org.springframework.boot

3 spring-boot-starter-parent

4 2.0.4.RELEASE

5

6

7

8

9 UTF-8

10 UTF-8

11 1.8

12 2.2.0

13 1.0.5

14

15

16

17

18 org.springframework.boot

19 spring-boot-starter-web

20

21

22 org.springframework.boot

23 spring-boot-devtools

24

25

26

27 com.baomidou

28 mybatisplus-spring-boot-starter

29 ${mybatisplus-spring-boot-starter.version}

30

31

32 com.baomidou

33 mybatis-plus

34 ${mybatisplus.version}

35

36

37

38

39 mysql

40 mysql-connector-java

41 runtime

42

43

44 org.springframework.boot

45 spring-boot-starter-tomcat

46 provided

47

48

49 org.springframework.boot

50 spring-boot-starter-test

51 test

52

53

54

55 com.alibaba

56 druid

57 1.1.9

58

59

application.yml 文件

1 spring:2 datasource:3 url: jdbc:mysql://xxxx/selll?useUnicode=true&characterEncoding=utf-8&useSSL=false4 username: root5 password: xxx6 driver-class-name: com.mysql.jdbc.Driver7 platform: mysql8 type: com.alibaba.druid.pool.DruidDataSource9 # 下面为连接池的补充设置,应用到上面所有数据源中10 # 初始化大小,最小,最大11 initialSize: 112 minIdle: 313 maxActive: 2014 # 配置获取连接等待超时的时间15 maxWait: 6000016 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒17 timeBetweenEvictionRunsMillis: 6000018 # 配置一个连接在池中最小生存的时间,单位是毫秒19 minEvictableIdleTimeMillis: 3000020 validationQuery: select ‘x‘21 testWhileIdle: true22 testOnBorrow: false23 testOnReturn: false24 # 打开PSCache,并且指定每个连接上PSCache的大小25 poolPreparedStatements: true26 maxPoolPreparedStatementPerConnectionSize: 2027 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,‘wall‘用于防火墙28 filters: stat,wall,slf4j29 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录30 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500031 # 合并多个DruidDataSource的监控数据32 #useGlobalDataSourceStat: true33 server:34 port: 808035 mybatis-plus:36 mapper-locations: mapper/*.xml37 type-aliases-package: com.wsy.dcxt.pojo38 global-config:39 id-type: 040 field-strategy: 241 capital-mode: true42 refresh-mapper: true

数据源的配置

1 packagecom.wsy.dcxt.config.dao;2

3 importjava.beans.PropertyVetoException;4

5 importcom.alibaba.druid.pool.DruidDataSource;6 importorg.mybatis.spring.annotation.MapperScan;7 importorg.springframework.beans.factory.annotation.Value;8 importorg.springframework.boot.context.properties.ConfigurationProperties;9 importorg.springframework.context.annotation.Bean;10 importorg.springframework.context.annotation.Configuration;11

12 importjavax.sql.DataSource;13

14 /**

15 * 配置datasource到ioc容器里面16 *17 *@authorxiangze18 *19 */

20 @Configuration21 @MapperScan(basePackages = "com.wsy.dcxt.dao")22 public classDataSourceConfiguration {23 @Value("${spring.datasource.driver-class-name}")24 privateString jdbcDriver;25 @Value("${spring.datasource.url}")26 privateString jdbcUrl;27 @Value("${spring.datasource.username}")28 privateString jdbcUsername;29 @Value("${spring.datasource.password}")30 privateString jdbcPassword;31

32

33 /**

34 * 生成与spring-dao.xml对应的bean dataSource35 *36 *@return

37 *@throwsPropertyVetoException38 */

39 @Bean(name = "dataSource")40 @ConfigurationProperties(prefix = "spring.datasource")41 publicDataSource dataSource(){42 return newDruidDataSource();43 }44

45 }

Mybatis-Plus的配置

1 packagecom.wsy.dcxt.config.dao;2

3 importjava.io.IOException;4

5 importjavax.sql.DataSource;6 importorg.apache.ibatis.plugin.Interceptor;7 importcom.alibaba.druid.pool.DruidDataSource;8 importcom.baomidou.mybatisplus.MybatisSessionFactoryBuilder;9 importcom.baomidou.mybatisplus.entity.GlobalConfiguration;10 importcom.baomidou.mybatisplus.plugins.PaginationInterceptor;11 importcom.baomidou.mybatisplus.plugins.PerformanceInterceptor;12 importcom.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;13 importorg.apache.ibatis.session.SqlSessionFactory;14 importorg.slf4j.Logger;15 importorg.slf4j.LoggerFactory;16 importorg.springframework.beans.factory.annotation.Autowired;17 importorg.springframework.beans.factory.annotation.Qualifier;18 importorg.springframework.beans.factory.annotation.Value;19 importorg.springframework.context.annotation.Bean;20 importorg.springframework.context.annotation.Configuration;21 importorg.springframework.core.io.support.PathMatchingResourcePatternResolver;22 importorg.springframework.core.io.support.ResourcePatternResolver;23 importorg.springframework.jdbc.datasource.DataSourceTransactionManager;24

25 @Configuration26 public classMybatisPlusConfig {27 private static final Logger log= LoggerFactory.getLogger(DataSourceConfiguration.class);28 @Autowired29 privateDataSource dataSource;30 @Value("${mybatis-plus.global-config.id-type}")31 privateInteger idType;32 @Value("${mybatis-plus.global-config.field-strategy}")33 private intfieldStrategy;34 @Value("${mybatis-plus.global-config.capital-mode}")35 private booleancapitalMode;36 @Value("${mybatis-plus.mapper-locations}")37 privateString mapperLocations;38 @Value("${mybatis-plus.type-aliases-package}")39 privateString typeAliasesPackage;40 @Value("${mybatis-plus.global-config.refresh-mapper}")41 private booleanrefreshMapper;42

43 //mybatis plus 全局配置

44 @Bean(name = "globalConfig")45 publicGlobalConfiguration globalConfiguration(){46 log.info("初始化GlobalConfiguration");47 GlobalConfiguration configuration=newGlobalConfiguration();48 //主键策略

49 configuration.setRefresh(refreshMapper);50 configuration.setIdType(idType);51 //字段策略

52 configuration.setFieldStrategy(fieldStrategy);53 //数据库大写 下划线转换

54 configuration.setCapitalMode(capitalMode);55 returnconfiguration;56 }57 @Bean(name = "sqlSessionFactory")58 public SqlSessionFactory createSqlSessionFactoryBean(@Qualifier(value = "globalConfig") GlobalConfiguration configuration) throwsException{59 log.info("初始化SqlSessionFactory");60 MybatisSqlSessionFactoryBean sqlSessionFactoryBean=newMybatisSqlSessionFactoryBean();61 sqlSessionFactoryBean.setDataSource(dataSource);62 Interceptor[] interceptor={newPaginationInterceptor()};63 sqlSessionFactoryBean.setPlugins(interceptor);64 ResourcePatternResolver resolver=newPathMatchingResourcePatternResolver();65 try{66 sqlSessionFactoryBean.setGlobalConfig(configuration);67 sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));68 sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);69 returnsqlSessionFactoryBean.getObject();70 }catch(Exception e){71 e.printStackTrace();72 }73 returnsqlSessionFactoryBean.getObject();74 }75 @Bean(name = "transactionManager")76 publicDataSourceTransactionManager transactionManager(){77 log.info("初始化transactionManager");78 return newDataSourceTransactionManager(dataSource);79 }80

81

82

83

84 }

Druid对于性能检测的配置

DruidStatFilter

1 packagecom.wsy.dcxt.config.dao;2

3 importcom.alibaba.druid.support.http.WebStatFilter;4

5 importjavax.servlet.annotation.WebFilter;6 importjavax.servlet.annotation.WebInitParam;7

8 @WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*",9 initParams ={10 @WebInitParam(name = "exclusions",11 value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*") })12 public class DruidStatFilter extendsWebStatFilter {13

14 }

DruidStatViewServlet

1 packagecom.wsy.dcxt.config.dao;2

3 importcom.alibaba.druid.support.http.StatViewServlet;4

5 importjavax.servlet.annotation.WebInitParam;6 importjavax.servlet.annotation.WebServlet;7

8 /**

9 * Druid 的数据源状态监控10 */

11 @WebServlet(urlPatterns = "/druid/*",12 initParams ={13 @WebInitParam(name = "allow",value = "127.0.0.1"),14 @WebInitParam(name = "deny",value = "192.168.1.3"),15 @WebInitParam(name ="loginUsername",value = "admin"),16 @WebInitParam(name = "loginPassword",value = "123456"),17 @WebInitParam(name = "resetEnable",value = "false")//禁止html页面上reset All功能

18 })19 public class DruidStatViewServlet extendsStatViewServlet {20 private static final long serialVersionUID = 1L;21 }

打开浏览器,输入配置allow的ip 用户名 密码 即可访问到性能检测面板

注: 记得在主类上添加

@ServletComponentScan 注解 不然会报404

对于传统的xml配置.测试了一个查看所有用户的方法

1 packagecom.wsy.dcxt.dao;2

3 importcom.wsy.dcxt.pojo.User;4 importcom.baomidou.mybatisplus.mapper.BaseMapper;5 importorg.apache.ibatis.annotations.Insert;6

7 importjava.util.List;8

9 public interface UserMapper extends BaseMapper{10

11

12 ListfindAllUsers();13 }

介绍UserMapper.java和UserMapper.xml

1 packagecom.wsy.dcxt.dao;2

3 importcom.wsy.dcxt.pojo.User;4 importcom.baomidou.mybatisplus.mapper.BaseMapper;5 importorg.apache.ibatis.annotations.Insert;6

7 importjava.util.List;8

9 public interface UserMapper extends BaseMapper{10

11

12 ListfindAllUsers();13 }

UserMapper.xml 记得统一 src/main/resouce/mapper (根据yml 文件的配置走)

1 <?xml version="1.0" encoding="UTF-8" ?>

2 /p>

4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

5

6

7 select *from user8

9

最后贴出测试类,开森一会儿

1 packagecom.wsy.dcxt.dao;2

3 importcom.wsy.dcxt.pojo.User;4 importcom.wsy.dcxt.service.UserService;5 importorg.junit.Test;6 importorg.junit.runner.RunWith;7 importorg.springframework.beans.factory.annotation.Autowired;8 importorg.springframework.boot.test.context.SpringBootTest;9 importorg.springframework.test.context.junit4.SpringRunner;10

11 importjava.util.List;12

13 import staticorg.junit.Assert.assertEquals;14

15 @SpringBootTest16 @RunWith(SpringRunner.class)17 public classTestUserMapper {18 @Autowired19 privateUserMapper userMapper;20 @Test21 public voidtestMapper(){22 List users =userMapper.findAllUsers();23 assertEquals(3,users.size());24

25

26 }27 @Test28 public voidinsertUser(){29 User user =newUser();30 user.setPassword("123");31 user.setUsername("90");32 int result=userMapper.insert(user);33 System.out.println(result);34

35 }36 }

好多次的InvalidBound 超级神奇 有这么几处需要切记!切记!

<1>,Mapper.java的方法和mapper.xml的方法是否匹配

<2>,namespace 是否填写正确

<3>,yml 中 读取mapper.xml的路径是否正确

<4>,mapperScan注释是否调用

最后

以上就是平常板凳为你收集整理的druid mysql配置详解_springboot+druid+mybatis-Plus 配置详解的全部内容,希望文章能够帮你解决druid mysql配置详解_springboot+druid+mybatis-Plus 配置详解所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(43)

评论列表共有 0 条评论

立即
投稿
返回
顶部