正文

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

回到顶部

 

回到顶部

springboot的pom文件

复制代码
 1  <parent>
 2         <groupId>org.springframework.boot</groupId>
 3         <artifactId>spring-boot-starter-parent</artifactId>
 4         <version>2.0.4.RELEASE</version>
 5         <relativePath/> <!-- lookup parent from repository -->
 6     </parent>
 7 
 8     <properties>
 9         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
10         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
11         <java.version>1.8</java.version>
12         <mybatisplus.version>2.2.0</mybatisplus.version>
13         <mybatisplus-spring-boot-starter.version>1.0.5</mybatisplus-spring-boot-starter.version>
14     </properties>
15 
16     <dependencies>
17         <dependency>
18             <groupId>org.springframework.boot</groupId>
19             <artifactId>spring-boot-starter-web</artifactId>
20         </dependency>
21         <dependency>
22             <groupId>org.springframework.boot</groupId>
23             <artifactId>spring-boot-devtools</artifactId>
24         </dependency>
25         <!--mybatis plus start-->
26         <dependency>
27             <groupId>com.baomidou</groupId>
28             <artifactId>mybatisplus-spring-boot-starter</artifactId>
29             <version>${mybatisplus-spring-boot-starter.version}</version>
30         </dependency>
31         <dependency>
32             <groupId>com.baomidou</groupId>
33             <artifactId>mybatis-plus</artifactId>
34             <version>${mybatisplus.version}</version>
35         </dependency>
36         <!--mybatis-plus end-->
37 
38         <dependency>
39             <groupId>mysql</groupId>
40             <artifactId>mysql-connector-java</artifactId>
41             <scope>runtime</scope>
42         </dependency>
43         <dependency>
44             <groupId>org.springframework.boot</groupId>
45             <artifactId>spring-boot-starter-tomcat</artifactId>
46             <scope>provided</scope>
47         </dependency>
48         <dependency>
49             <groupId>org.springframework.boot</groupId>
50             <artifactId>spring-boot-starter-test</artifactId>
51             <scope>test</scope>
52         </dependency>
53         <!--配置druid数据源-->
54         <dependency>
55             <groupId>com.alibaba</groupId>
56             <artifactId>druid</artifactId>
57             <version>1.1.9</version>
58         </dependency>
59     </dependencies>
复制代码
回到顶部

application.yml 文件

复制代码
 1 spring:
 2   datasource:
 3     url: jdbc:mysql://xxxx/selll?useUnicode=true&characterEncoding=utf-8&useSSL=false
 4     username: root
 5     password: xxx
 6     driver-class-name: com.mysql.jdbc.Driver
 7     platform: mysql
 8     type: com.alibaba.druid.pool.DruidDataSource
 9     # 下面为连接池的补充设置,应用到上面所有数据源中
10     # 初始化大小,最小,最大
11     initialSize: 1
12     minIdle: 3
13     maxActive: 20
14     # 配置获取连接等待超时的时间
15     maxWait: 60000
16     # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
17     timeBetweenEvictionRunsMillis: 60000
18     # 配置一个连接在池中最小生存的时间,单位是毫秒
19     minEvictableIdleTimeMillis: 30000
20     validationQuery: select 'x'
21     testWhileIdle: true
22     testOnBorrow: false
23     testOnReturn: false
24     # 打开PSCache,并且指定每个连接上PSCache的大小
25     poolPreparedStatements: true
26     maxPoolPreparedStatementPerConnectionSize: 20
27     # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
28     filters: stat,wall,slf4j
29     # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
30     connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
31     # 合并多个DruidDataSource的监控数据
32     #useGlobalDataSourceStat: true
33 server:
34   port: 8080
35 mybatis-plus:
36   mapper-locations: mapper/*.xml
37   type-aliases-package: com.wsy.dcxt.pojo
38   global-config:
39     id-type: 0
40     field-strategy: 2
41     capital-mode: true
42     refresh-mapper: true
复制代码
回到顶部

数据源的配置

复制代码
 1 package com.wsy.dcxt.config.dao;
 2 
 3 import java.beans.PropertyVetoException;
 4 
 5 import com.alibaba.druid.pool.DruidDataSource;
 6 import org.mybatis.spring.annotation.MapperScan;
 7 import org.springframework.beans.factory.annotation.Value;
 8 import org.springframework.boot.context.properties.ConfigurationProperties;
 9 import org.springframework.context.annotation.Bean;
10 import org.springframework.context.annotation.Configuration;
11 
12 import javax.sql.DataSource;
13 
14 /**
15  * 配置datasource到ioc容器里面
16  * 
17  * @author xiangze
18  *
19  */
20 @Configuration
21 @MapperScan(basePackages = "com.wsy.dcxt.dao")
22 public class DataSourceConfiguration {
23     @Value("${spring.datasource.driver-class-name}")
24     private String jdbcDriver;
25     @Value("${spring.datasource.url}")
26     private String jdbcUrl;
27     @Value("${spring.datasource.username}")
28     private String jdbcUsername;
29     @Value("${spring.datasource.password}")
30     private String jdbcPassword;
31 
32 
33     /**
34      * 生成与spring-dao.xml对应的bean dataSource
35      * 
36      * @return
37      * @throws PropertyVetoException
38      */
39     @Bean(name = "dataSource")
40     @ConfigurationProperties(prefix = "spring.datasource")
41     public DataSource dataSource(){
42         return new DruidDataSource();
43     }
44 
45 }
复制代码
回到顶部

Mybatis-Plus的配置

复制代码
 1 package com.wsy.dcxt.config.dao;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.sql.DataSource;
 6 import org.apache.ibatis.plugin.Interceptor;
 7 import com.alibaba.druid.pool.DruidDataSource;
 8 import com.baomidou.mybatisplus.MybatisSessionFactoryBuilder;
 9 import com.baomidou.mybatisplus.entity.GlobalConfiguration;
10 import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
11 import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
12 import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
13 import org.apache.ibatis.session.SqlSessionFactory;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16 import org.springframework.beans.factory.annotation.Autowired;
17 import org.springframework.beans.factory.annotation.Qualifier;
18 import org.springframework.beans.factory.annotation.Value;
19 import org.springframework.context.annotation.Bean;
20 import org.springframework.context.annotation.Configuration;
21 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
22 import org.springframework.core.io.support.ResourcePatternResolver;
23 import org.springframework.jdbc.datasource.DataSourceTransactionManager;
24 
25 @Configuration
26 public class MybatisPlusConfig {
27     private static final Logger log= LoggerFactory.getLogger(DataSourceConfiguration.class);
28     @Autowired
29     private DataSource dataSource;
30     @Value("${mybatis-plus.global-config.id-type}")
31     private Integer idType;
32     @Value("${mybatis-plus.global-config.field-strategy}")
33     private int fieldStrategy;
34     @Value("${mybatis-plus.global-config.capital-mode}")
35     private boolean capitalMode;
36     @Value("${mybatis-plus.mapper-locations}")
37     private String mapperLocations;
38     @Value("${mybatis-plus.type-aliases-package}")
39     private String typeAliasesPackage;
40     @Value("${mybatis-plus.global-config.refresh-mapper}")
41     private boolean refreshMapper;
42 
43     //mybatis plus 全局配置
44     @Bean(name = "globalConfig")
45     public GlobalConfiguration globalConfiguration(){
46         log.info("初始化GlobalConfiguration");
47         GlobalConfiguration configuration=new GlobalConfiguration();
48         //主键策略
49         configuration.setRefresh(refreshMapper);
50         configuration.setIdType(idType);
51         //字段策略
52         configuration.setFieldStrategy(fieldStrategy);
53         //数据库大写 下划线转换
54         configuration.setCapitalMode(capitalMode);
55         return configuration;
56     }
57     @Bean(name = "sqlSessionFactory")
58     public SqlSessionFactory createSqlSessionFactoryBean(@Qualifier(value = "globalConfig") GlobalConfiguration configuration) throws Exception{
59         log.info("初始化SqlSessionFactory");
60         MybatisSqlSessionFactoryBean sqlSessionFactoryBean=new MybatisSqlSessionFactoryBean();
61         sqlSessionFactoryBean.setDataSource(dataSource);
62         Interceptor[] interceptor={new PaginationInterceptor()};
63         sqlSessionFactoryBean.setPlugins(interceptor);
64         ResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
65         try{
66             sqlSessionFactoryBean.setGlobalConfig(configuration);
67             sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));
68             sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
69             return sqlSessionFactoryBean.getObject();
70         }catch (Exception e){
71             e.printStackTrace();
72         }
73         return sqlSessionFactoryBean.getObject();
74     }
75     @Bean(name = "transactionManager")
76     public DataSourceTransactionManager transactionManager(){
77         log.info("初始化transactionManager");
78         return new DataSourceTransactionManager(dataSource);
79     }
80 
81 
82 
83 
84 }
复制代码

 Druid对于性能检测的配置

 DruidStatFilter  

 

复制代码
 1 package com.wsy.dcxt.config.dao;
 2 
 3 import com.alibaba.druid.support.http.WebStatFilter;
 4 
 5 import javax.servlet.annotation.WebFilter;
 6 import javax.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 extends WebStatFilter {
13 
14 }
复制代码
回到顶部

 DruidStatViewServlet

复制代码
 1 package com.wsy.dcxt.config.dao;
 2 
 3 import com.alibaba.druid.support.http.StatViewServlet;
 4 
 5 import javax.servlet.annotation.WebInitParam;
 6 import javax.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 extends StatViewServlet {
20     private static final long serialVersionUID = 1L;
21 }
复制代码

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

注: 记得在主类上添加

@ServletComponentScan 注解 不然会报404

 

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

复制代码
 1 package com.wsy.dcxt.dao;
 2 
 3 import com.wsy.dcxt.pojo.User;
 4 import com.baomidou.mybatisplus.mapper.BaseMapper;
 5 import org.apache.ibatis.annotations.Insert;
 6 
 7 import java.util.List;
 8 
 9 public interface UserMapper extends BaseMapper<User>{
10 
11 
12     List<User> findAllUsers();
13 }
复制代码

介绍UserMapper.java和UserMapper.xml

复制代码
 1 package com.wsy.dcxt.dao;
 2 
 3 import com.wsy.dcxt.pojo.User;
 4 import com.baomidou.mybatisplus.mapper.BaseMapper;
 5 import org.apache.ibatis.annotations.Insert;
 6 
 7 import java.util.List;
 8 
 9 public interface UserMapper extends BaseMapper<User>{
10 
11 
12     List<User> findAllUsers();
13 }
复制代码

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

复制代码
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper
3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <mapper namespace="com.wsy.dcxt.dao.UserMapper">
6     <select id="findAllUsers" resultType="user">
7         select * from user
8     </select>
9 </mapper>
复制代码
回到顶部

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

复制代码
 1 package com.wsy.dcxt.dao;
 2 
 3 import com.wsy.dcxt.pojo.User;
 4 import com.wsy.dcxt.service.UserService;
 5 import org.junit.Test;
 6 import org.junit.runner.RunWith;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.boot.test.context.SpringBootTest;
 9 import org.springframework.test.context.junit4.SpringRunner;
10 
11 import java.util.List;
12 
13 import static org.junit.Assert.assertEquals;
14 
15 @SpringBootTest
16 @RunWith(SpringRunner.class)
17 public class TestUserMapper {
18     @Autowired
19     private UserMapper userMapper;
20     @Test
21    public void testMapper(){
22        List<User> users = userMapper.findAllUsers();
23        assertEquals(3,users.size());
24 
25 
26     }
27     @Test
28     public void insertUser(){
29         User user =new User();
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注释是否调用

 留下 项目github 地址: https://github.com/shinefairy/dcxt

 

转自:https://www.cnblogs.com/shine-rainbow/p/9618100.html