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

springboot的pom文件

  <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<mybatisplus.version>2.2.0</mybatisplus.version>
<mybatisplus-spring-boot-starter.version>1.0.5</mybatisplus-spring-boot-starter.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!--mybatis plus start-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>${mybatisplus-spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybatisplus.version}</version>
</dependency>
<!--mybatis-plus end--> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--配置druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
</dependencies>

application.yml 文件

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

数据源的配置

 package com.wsy.dcxt.config.dao;

 import java.beans.PropertyVetoException;

 import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; /**
* 配置datasource到ioc容器里面
*
* @author xiangze
*
*/
@Configuration
@MapperScan(basePackages = "com.wsy.dcxt.dao")
public class DataSourceConfiguration {
@Value("${spring.datasource.driver-class-name}")
private String jdbcDriver;
@Value("${spring.datasource.url}")
private String jdbcUrl;
@Value("${spring.datasource.username}")
private String jdbcUsername;
@Value("${spring.datasource.password}")
private String jdbcPassword; /**
* 生成与spring-dao.xml对应的bean dataSource
*
* @return
* @throws PropertyVetoException
*/
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(){
return new DruidDataSource();
} }

Mybatis-Plus的配置

 package com.wsy.dcxt.config.dao;

 import java.io.IOException;

 import javax.sql.DataSource;
import org.apache.ibatis.plugin.Interceptor;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.MybatisSessionFactoryBuilder;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; @Configuration
public class MybatisPlusConfig {
private static final Logger log= LoggerFactory.getLogger(DataSourceConfiguration.class);
@Autowired
private DataSource dataSource;
@Value("${mybatis-plus.global-config.id-type}")
private Integer idType;
@Value("${mybatis-plus.global-config.field-strategy}")
private int fieldStrategy;
@Value("${mybatis-plus.global-config.capital-mode}")
private boolean capitalMode;
@Value("${mybatis-plus.mapper-locations}")
private String mapperLocations;
@Value("${mybatis-plus.type-aliases-package}")
private String typeAliasesPackage;
@Value("${mybatis-plus.global-config.refresh-mapper}")
private boolean refreshMapper; //mybatis plus 全局配置
@Bean(name = "globalConfig")
public GlobalConfiguration globalConfiguration(){
log.info("初始化GlobalConfiguration");
GlobalConfiguration configuration=new GlobalConfiguration();
//主键策略
configuration.setRefresh(refreshMapper);
configuration.setIdType(idType);
//字段策略
configuration.setFieldStrategy(fieldStrategy);
//数据库大写 下划线转换
configuration.setCapitalMode(capitalMode);
return configuration;
}
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory createSqlSessionFactoryBean(@Qualifier(value = "globalConfig") GlobalConfiguration configuration) throws Exception{
log.info("初始化SqlSessionFactory");
MybatisSqlSessionFactoryBean sqlSessionFactoryBean=new MybatisSqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
Interceptor[] interceptor={new PaginationInterceptor()};
sqlSessionFactoryBean.setPlugins(interceptor);
ResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
try{
sqlSessionFactoryBean.setGlobalConfig(configuration);
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));
sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
return sqlSessionFactoryBean.getObject();
}catch (Exception e){
e.printStackTrace();
}
return sqlSessionFactoryBean.getObject();
}
@Bean(name = "transactionManager")
public DataSourceTransactionManager transactionManager(){
log.info("初始化transactionManager");
return new DataSourceTransactionManager(dataSource);
} }

Druid对于性能检测的配置

 DruidStatFilter  

 package com.wsy.dcxt.config.dao;

 import com.alibaba.druid.support.http.WebStatFilter;

 import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam; @WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*",
initParams = {
@WebInitParam(name = "exclusions",
value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*") })
public class DruidStatFilter extends WebStatFilter { }

DruidStatViewServlet

 package com.wsy.dcxt.config.dao;

 import com.alibaba.druid.support.http.StatViewServlet;

 import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet; /**
* Druid 的数据源状态监控
*/
@WebServlet(urlPatterns = "/druid/*",
initParams = {
@WebInitParam(name = "allow",value = "127.0.0.1"),
@WebInitParam(name = "deny",value = "192.168.1.3"),
@WebInitParam(name ="loginUsername",value = "admin"),
@WebInitParam(name = "loginPassword",value = "123456"),
@WebInitParam(name = "resetEnable",value = "false")//禁止html页面上reset All功能
})
public class DruidStatViewServlet extends StatViewServlet {
private static final long serialVersionUID = 1L;
}

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

注: 记得在主类上添加

@ServletComponentScan 注解 不然会报404

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

 package com.wsy.dcxt.dao;

 import com.wsy.dcxt.pojo.User;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Insert; import java.util.List; public interface UserMapper extends BaseMapper<User>{ List<User> findAllUsers();
}

介绍UserMapper.java和UserMapper.xml

 package com.wsy.dcxt.dao;

 import com.wsy.dcxt.pojo.User;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Insert; import java.util.List; public interface UserMapper extends BaseMapper<User>{ List<User> findAllUsers();
}

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

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wsy.dcxt.dao.UserMapper">
<select id="findAllUsers" resultType="user">
select * from user
</select>
</mapper>

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

 package com.wsy.dcxt.dao;

 import com.wsy.dcxt.pojo.User;
import com.wsy.dcxt.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.junit.Assert.assertEquals; @SpringBootTest
@RunWith(SpringRunner.class)
public class TestUserMapper {
@Autowired
private UserMapper userMapper;
@Test
public void testMapper(){
List<User> users = userMapper.findAllUsers();
assertEquals(3,users.size()); }
@Test
public void insertUser(){
User user =new User();
user.setPassword("123");
user.setUsername("90");
int result=userMapper.insert(user);
System.out.println(result); }
}

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

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

<2>,namespace 是否填写正确

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

<4>,mapperScan注释是否调用

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

springboot+druid+mybatis-Plus 配置详解的更多相关文章

  1. SpringBoot与Mybatis整合实例详解

    介绍 从Spring Boot项目名称中的Boot可以看出来,SpringBoot的作用在于创建和启动新的基于Spring框架的项目,它的目的是帮助开发人员很容易的创建出独立运行的产品和产品级别的基于 ...

  2. SSM ( Spring 、 SpringMVC 和 Mybatis )配置详解

    使用 SSM ( Spring . SpringMVC 和 Mybatis )已经有三个多月了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地方.之前没 ...

  3. 笔记:MyBatis XML配置详解

    MyBatis 的配置文件包含了影响 MyBatis 行为甚深的设置(settings)和属性(properties)信息.文档的顶层结构如下: configuration 配置 properties ...

  4. Spring Boot中使用MyBatis注解配置详解(1)

    之前在Spring Boot中整合MyBatis时,采用了注解的配置方式,相信很多人还是比较喜欢这种优雅的方式的,也收到不少读者朋友的反馈和问题,主要集中于针对各种场景下注解如何使用,下面就对几种常见 ...

  5. Mybatis Generator配置详解

    参考:http://www.jianshu.com/p/e09d2370b796 http://mbg.cndocs.tk <?xml version="1.0" encod ...

  6. 关于mybatis缓存配置详解

    一级缓存: 一级缓存是默认的. 测试:在WEB页面同一个查询执行两次从日志里面看同样的sql查询执行两次. 2次sql查询,看似我们使用了同一个sqlSession,但是实际上因为我们的dao继承了S ...

  7. IntelliJ IDEA 2017版 spring-boot加载jsp配置详解(详细图文实例)

    一.创建项目 (File--->New-->Project) 2.项目配置内容 3.选择配置项目的Group包名,Artifact项目名称 4.选择项目类型为web类型 5.创建成功,点击 ...

  8. Spring Boot中使用MyBatis注解配置详解

    传参方式 下面通过几种不同传参方式来实现前文中实现的插入操作. 使用@Param 在之前的整合示例中我们已经使用了这种最简单的传参方式,如下: @Insert("INSERT INTO US ...

  9. Spring Boot教程(三十九)使用MyBatis注解配置详解(2)

    增删改查 MyBatis针对不同的数据库操作分别提供了不同的注解来进行配置,在之前的示例中演示了@Insert,下面针对User表做一组最基本的增删改查作为示例: public interface U ...

  10. Spring Boot教程(三十八)使用MyBatis注解配置详解(1)

    之前在Spring Boot中整合MyBatis时,采用了注解的配置方式,相信很多人还是比较喜欢这种优雅的方式的,也收到不少读者朋友的反馈和问题,主要集中于针对各种场景下注解如何使用,下面就对几种常见 ...

随机推荐

  1. 02: kubernetes安装

    参考官网:http://docs.kubernetes.org.cn/ 1.1 集群部署 1.集群结构 192.168.56.11 linux-node1 linux-node1.example.co ...

  2. 缓存---LRU算法实现

    2.LRU   以下是基于双向链表+HashMap的LRU算法实现,对算法的解释如下:   设置一个map存放对应的键和值,同时设置一个双向链表,来保存最近最久未使用的关系,如果访问一个键,键存在于m ...

  3. jsp页面中JSTL如何处理日期格式

    引入fmt标签 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> 格 ...

  4. UnknownPropertyException(Yii2)

    在class里面的rule有属性,但是没声明

  5. ERP和MES系统的区别和关系?

    1.ERP和MES的区别:ERP(Enterprise Resources Planning)是企业资源计划,它是在物料需求计划MRP(Material Requirement Planning)和制 ...

  6. laravel中间件失效,配置文件重新加载

    composer dump-autoload php artisan cache:clear 清理视图缓存 php atisan view:clear 清除运行缓存 php artisan cache ...

  7. Linux-定时任务排查

    前段时间,哥们的服务器被人反弹了shell,由于反弹的地址不可达,系统总是会发送一条mail邮件到root账户,导致入侵行为被发现,由于反弹的动作是通过crontab来定时执行的,所以来梳理下cron ...

  8. passwd 修改用户密码 / chpasswd 批量更新用户密码

    passwd 修改用户密码 1.命令功能 passwd 修改用户密码及密码过期时间等信息. 2.语法格式 passwd  option  username passwd   选项   用户名 选项说明 ...

  9. Mysterious Crime CodeForces - 1043D (思维+组合数学)

    Acingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody ...

  10. 【vue2.x基础】用npm起一个完整的项目

    1. 安装vue npm install vue -g 2.  安装vue-cli脚手架 npm install vue-cli -g 3. 安装webpack npm install webpack ...