MyBatis-Plus+Druid配置及应用详解

Mybatis-Plus的配置

1.Maven插件

velocity-engine-core是mybatis-plus自动生成代码所依赖的模板(不用自动生成代码功能可不用)

  <dependency>
  <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-boot-starter</artifactId>
   <version>3.0.6</version>
 </dependency>
 <dependency>
  <groupId>org.apache.velocity</groupId>
  <artifactId>velocity-engine-core</artifactId>
  <version>2.2</version>
 </dependency>

2.application.properties配置

和普通mysql配置相同,没有额外配置

#mysql 连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

3.Mapper相关注解

@MapperScan中直接mapper文件所在的package

@SpringBootApplication
@EnableTransactionManagement
@EnableEurekaClient
@MapperScan("com.example.demo.dao")
public class DemoApplication {

 public static void main(String[] args) {
 SpringApplication.run(DemoApplication.class, args);
 }
}

4.创建数据库表

5.创建JavaBean(推荐使用Lombok插件方式) - Model层

@Data
@TableName("area")
@ToString(callSuper=true, includeFieldNames=true)
@AllArgsConstructor
@NoArgsConstructor
public class Area implements Serializable{

 private static final long serialVersionUID = 1L;
 private String id;
 private String name;
 private int sort;
}

6.创建Mapper - DAO层

只有自定义SQL时,mapper中才有内容, 使用mybatis-plus自带CRUD语句或者构造器拼接语句时, mapper通常为空

public interface AreaMapper extends BaseMapper<Area> {

 //通过mybatis-plus提供的注解,直接自定义SQL
 @Select("select name from area where sort > ${sort}")
 List<String> getBySort2(@Param("sort")int sort);
}

8.创建逻辑接口 - Service层

public interface IAreaService {

 public Area getById(String id);

 public List<Area> selectAll();

 public int updateByPrimaryKeySelective(Area record);

 public int deleteByPrimaryKey(String id);

 public int insertSelective(Area record);

 public List<Area> getBySort();

 public List<String> getBySort2(int sort);

}

9.创建逻辑类 - Service层

Mybatis-Plus使用SQL的3种常见方法:
a. 使用mybatis-plus自带CRUD方法: 直接用mapper的自带方法
b. 使用mybatis-plus提供的条件构造器,拼接where条件
c. 使用@Select,@Update等注解, 自己写SQL+参数

@Service
public class AreaServiceImpl implements IAreaService {

 @Autowired
 public AreaMapper areaMapper;

 //使用mybatis-plus自带CRUD方法
 @Override
 public Area getById(String id) {
 return areaMapper.selectById(id);
 } 

 @Override
 public List<Area> selectAll() {
 return areaMapper.selectList(null);
 }

 @Override
 @Transactional
 public int updateByPrimaryKeySelective(Area record) {
 return areaMapper.updateById(record);
 }

 @Override
 public int deleteByPrimaryKey(String id) {
 return areaMapper.deleteById(id);
 }

 @Override
 public int insertSelective(Area record) {
 return areaMapper.insert(record);
 }

 //使用mybatis-plus提供的条件构造器,拼接条件
 @Override
 public List<Area> getBySort(){
 QueryWrapper<Area> queryWrapper = new QueryWrapper<>();
 queryWrapper.lambda().gt(Area::getSort, 40)
  .lt(Area::getSort, 80);
 return areaMapper.selectList(queryWrapper);
 }

 //通过mybatis-plus提供的注解,直接自定义SQL(定义在mapper中)
 @Override
 public List<String> getBySort2(int sort){
 return areaMapper.getBySort2(sort);

 }

}

10.创建接口 - Controller层

@RestController
@RequestMapping("/area")
public class AreaController {

 @Autowired
 private IAreaService areaService;

 @Autowired
 private DbpropertiesService dbproService;

 @Autowired
 private Area area;

 @Resource
 protected HttpServletRequest request;

 @RequestMapping(value = "/getAreaInfo",method=RequestMethod.GET)
 public Area getAreaInfo(@RequestParam(value="id") String id) {
 area = areaService.getById(id);
 return area;
 }

 @RequestMapping(value = "/getAreaAllInfo",method=RequestMethod.GET)
 public List<Area> getAreaInfo() {
 List<Area> arlist = areaService.selectAll();
 return arlist;
 }

 @RequestMapping(value ="/updateAreaName",method=RequestMethod.PUT)
 public int updateAreaInfo(@RequestParam(value="id") String id,@RequestParam(value="name",required=false) String name,@RequestParam(value="sort",required=false) Integer sort) {
 area.setId(id);
 area.setName(name);
 area.setSort(sort);
 int ar = areaService.updateByPrimaryKeySelective(area);
 return ar;
 }

 @RequestMapping(value ="/deleteAreaName",method=RequestMethod.DELETE)
 public int deleteAreaInfo(@RequestParam(value="id") String id) {
 int ar = areaService.deleteByPrimaryKey(id);
 return ar;
 }

// @RequestMapping(value ="/insertAreaName",method=RequestMethod.POST)
// public int insertAreaInfo(@RequestParam(value="id") String id,@RequestParam(value="name",required=false) String name,@RequestParam(value="sort",required=false) Integer sort) {
// area.setId(id);
// area.setName(name);
// area.setSort(sort);
// int ar = areaService.insertSelective(area);
// return ar;
// } 

 @RequestMapping(value ="/insertAreaName",method=RequestMethod.POST)
 public int insertAreaInfo(@RequestBody Area area) {
 int ar = areaService.insertSelective(area);
 return ar;
 }

 @RequestMapping(value ="/selectBySort",method=RequestMethod.GET)
 public List<Area> selectAreaSort() {
 List<Area> arList = areaService.getBySort();
 return arList;
 }

 @RequestMapping(value ="/selectBySort2",method=RequestMethod.GET)
 public List<String> selectAreaSort2(@RequestParam(value="sort") int sort) {
 List<String> arList = areaService.getBySort2(sort);
 return arList;
 }
}

参考文档:
https://mp.baomidou.com/

数据源datasource

数据源是数据库连接的规范接口

Springboot默认支持4种数据源类型,定义在 org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration 中,分别是:

org.apache.tomcat.jdbc.pool.DataSource
 com.zaxxer.hikari.HikariDataSource
 org.apache.commons.dbcp.BasicDataSource
 org.apache.commons.dbcp2.BasicDataSource

在不指定数据源类型时, SpringBoot默认使用tomcat.jdbc

如果需要使用第三方数据源, 比如Druid, 步骤如下:

Druid的配置

1.Maven配置

 <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.1.3</version>
  </dependency>

2.application.properties配置

spring.datasource.type需要指定为Druid
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

其他的Druid自有属性,可以写在properties中也可以写在Druid的配置类中

@ConfigurationProperties(prefix = "spring.datasource")
public class DruidConfiguration {

 private String url;
 private String username;
 private String password;
 private String driverClassName;
 private int initialSize = 5;
 private int minIdle = 5;
 private int maxActive = 10;
 private int maxWait = 2;
 private int timeBetweenEvictionRunsMillis = 1000 * 60;
 private int minEvictableIdleTimeMillis = 1000 * 60 * 30;
 private String validationQuery;
 private boolean testWhileIdle = false;
 private boolean testOnBorrow = true;
 private boolean testOnReturn = false;
 private boolean poolPreparedStatements = false;
 private int maxPoolPreparedStatementPerConnectionSize = -1;
 private String filters;
 private boolean useGlobalDataSourceStat = false;
 private String connectionProperties;

3.定义数据源

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSource2Config {

 private String url;
 private String username;
 private String password;

 @Bean
 public DataSource getDataSource() {
 DruidDataSource dataSource = new DruidDataSource();
 dataSource.setUrl(url);
 dataSource.setUsername(username);// 用户名
 dataSource.setPassword(password);// 密码
 return dataSource;
 }

 public String getUrl() {
 return url;
 }

 public void setUrl(String url) {
 this.url = url;
 }

 public String getUsername() {
 return username;
 }

 public void setUsername(String username) {
 this.username = username;
 }

 public String getPassword() {
 return password;
 }

 public void setPassword(String password) {
 this.password = password;
 }
}

4.配置Druid的监控器和为事务管理器指定Druid数据源, 最终Configuration文件如下:

Druid监控配置:

ServletRegistrationBean
FilterRegistrationBean

事务管理器配置:
PlatformTransactionManager

package com.example.demo.dao.druid;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DruidConfiguration {

 @Bean
 public ServletRegistrationBean druidServlet() {
  //logger.info("init Druid Servlet Configuration ");
  ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
  servletRegistrationBean.setServlet(new StatViewServlet());
  servletRegistrationBean.addUrlMappings("/druid/*");
  Map<String, String> initParameters = new HashMap<String, String>();
  initParameters.put("loginUsername", "admin");
  initParameters.put("loginPassword", "admin");
  initParameters.put("resetEnable", "false");
  initParameters.put("allow", "");
  initParameters.put("deny", "");
  servletRegistrationBean.setInitParameters(initParameters);
  return servletRegistrationBean;
 }

 @Bean
 public FilterRegistrationBean filterRegistrationBean() {
  FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
  filterRegistrationBean.setFilter(new WebStatFilter());
  filterRegistrationBean.addUrlPatterns("/*");
  filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
  return filterRegistrationBean;
 }

 @Bean
 @Primary
 public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
  DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
  dataSourceTransactionManager.setDataSource(dataSource);
  return dataSourceTransactionManager;
 }

}

//Druid配置Bean
@Component
@ConfigurationProperties(prefix = "spring.datasource")
class DruidDataSourceProperties {

 private String url;
 private String username;
 private String password;
 private String driverClassName;
 private int initialSize = 5;
 private int minIdle = 5;
 private int maxActive = 10;
 private int maxWait = 2;
 private int timeBetweenEvictionRunsMillis = 1000 * 60;
 private int minEvictableIdleTimeMillis = 1000 * 60 * 30;
 private String validationQuery;
 private boolean testWhileIdle = false;
 private boolean testOnBorrow = true;
 private boolean testOnReturn = false;
 private boolean poolPreparedStatements = false;
 private int maxPoolPreparedStatementPerConnectionSize = -1;
 private String filters = "stat";
 private boolean useGlobalDataSourceStat = false;
 private String connectionProperties;

 @Bean  //声明其为Bean实例,将数据源设置为druid
 @Primary //在同样的DataSource中,首先使用被标注的DataSource
 public DataSource dataSource() {
  DruidDataSource datasource = new DruidDataSource();
  datasource.setUrl(url);
  datasource.setUsername(username);
  datasource.setPassword(password);
  datasource.setDriverClassName(driverClassName);

  //configuration
  datasource.setInitialSize(initialSize);
  datasource.setMinIdle(minIdle);
  datasource.setMaxActive(maxActive);
  datasource.setMaxWait(maxWait);
  datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  datasource.setValidationQuery(validationQuery);
  datasource.setTestWhileIdle(testWhileIdle);
  datasource.setTestOnBorrow(testOnBorrow);
  datasource.setTestOnReturn(testOnReturn);
  datasource.setPoolPreparedStatements(poolPreparedStatements);
  datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  try {
   datasource.setFilters(filters);
  } catch (SQLException e) {
   System.err.println("druid configuration initialization filter: " + e);
  }
  datasource.setConnectionProperties(connectionProperties);
  return datasource;
 }

 public String getUrl() {
  return url;
 }

 public void setUrl(String url) {
  this.url = url;
 }

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getDriverClassName() {
  return driverClassName;
 }

 public void setDriverClassName(String driverClassName) {
  this.driverClassName = driverClassName;
 }

 public int getInitialSize() {
  return initialSize;
 }

 public void setInitialSize(int initialSize) {
  this.initialSize = initialSize;
 }

 public int getMinIdle() {
  return minIdle;
 }

 public void setMinIdle(int minIdle) {
  this.minIdle = minIdle;
 }

 public int getMaxActive() {
  return maxActive;
 }

 public void setMaxActive(int maxActive) {
  this.maxActive = maxActive;
 }

 public int getMaxWait() {
  return maxWait;
 }

 public void setMaxWait(int maxWait) {
  this.maxWait = maxWait;
 }

 public int getTimeBetweenEvictionRunsMillis() {
  return timeBetweenEvictionRunsMillis;
 }

 public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
  this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
 }

 public int getMinEvictableIdleTimeMillis() {
  return minEvictableIdleTimeMillis;
 }

 public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
  this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
 }

 public String getValidationQuery() {
  return validationQuery;
 }

 public void setValidationQuery(String validationQuery) {
  this.validationQuery = validationQuery;
 }

 public boolean isTestWhileIdle() {
  return testWhileIdle;
 }

 public void setTestWhileIdle(boolean testWhileIdle) {
  this.testWhileIdle = testWhileIdle;
 }

 public boolean isTestOnBorrow() {
  return testOnBorrow;
 }

 public void setTestOnBorrow(boolean testOnBorrow) {
  this.testOnBorrow = testOnBorrow;
 }

 public boolean isTestOnReturn() {
  return testOnReturn;
 }

 public void setTestOnReturn(boolean testOnReturn) {
  this.testOnReturn = testOnReturn;
 }

 public boolean isPoolPreparedStatements() {
  return poolPreparedStatements;
 }

 public void setPoolPreparedStatements(boolean poolPreparedStatements) {
  this.poolPreparedStatements = poolPreparedStatements;
 }

 public int getMaxPoolPreparedStatementPerConnectionSize() {
  return maxPoolPreparedStatementPerConnectionSize;
 }

 public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
  this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
 }

 public String getFilters() {
  return filters;
 }

 public void setFilters(String filters) {
  this.filters = filters;
 }

 public boolean isUseGlobalDataSourceStat() {
  return useGlobalDataSourceStat;
 }

 public void setUseGlobalDataSourceStat(boolean useGlobalDataSourceStat) {
  this.useGlobalDataSourceStat = useGlobalDataSourceStat;
 }

 public String getConnectionProperties() {
  return connectionProperties;
 }

 public void setConnectionProperties(String connectionProperties) {
  this.connectionProperties = connectionProperties;
 }
}

5.Druid性能监控台
http://localhost:8092/druid/index.html

到此这篇关于MyBatis-Plus+Druid配置及应用详解的文章就介绍到这了,更多相关MyBatis-Plus Druid配置内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • MyBatis-Plus集成Druid环境搭建的详细教程

    一.简介 Mybatis-Plus是一款 MyBatis 动态 sql 自动注入 crud 简化 增 删 改 查 操作中间件.启动加载 XML 配置时注入 mybatis 单表 动态 SQL 操作 ,为简化开发工作.提高生产率而生.Mybatis-Plus 启动注入非拦截实现.性能更优. 1.1.原理 1.2.特性 无侵入:Mybatis-Plus 在 Mybatis 的基础上进行扩展,只做增强不做改变,引入 Mybatis-Plus 不会对您现有的 Mybatis 构架产生任何影响,而且 MP

  • MyBatis-Plus+Druid配置及应用详解

    Mybatis-Plus的配置 1.Maven插件 velocity-engine-core是mybatis-plus自动生成代码所依赖的模板(不用自动生成代码功能可不用) <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.6</version> </

  • IDEA的Mybatis Log Plugin插件配置和使用详解

    在使用Mybatis开发项目时,由于避免出现SQL注入,大部分情况下都是使用#{}占位符的方式传参. 所以日志打印SQL时,打印的也是占位符,如: 如果SQL比较复杂,参数又很多的话,要通过日志拼凑真正可执行的SQL还是件比较头痛的事情. 好在IDEA有款很不错的插件(Mybatis Log Plugin)可以解决上述问题. 插件安装 像其它插件一样,可选择在线安装和离线安装. 在线安装:搜索Mybatis Log Plugin,直接install即可.离线安装:可从:http://plugin

  • Mybatis环境配置及测试详解

    mybatis 3 | 参考文档 MyBatis 是一款优秀的持久层框架,它支持自定义 SQL.存储过程以及高级映射.MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作. MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型.接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录. 一.mybatis环境配置 1.通过maven的pom.xml文件引入mybatis需要的包 在其<depend

  • Java Fluent Mybatis 项目工程化与常规操作详解流程篇 上

    目录 前言 Maven依赖 配置文件调整 Knife4j配置 添加必要实体 增/改 总结 前言 接着上一篇,上篇已经测试通过,成功添加了数据.那么这篇主要是继续上一个项目,将项目进行工程化包装,增加一些必要配置,并且生成增删改查接口. GitHub代码仓库:GitHub仓库 Maven依赖 增加了druid数据库连接池,所以之前的配置文件也需要调整,下面会发出来. <dependency> <groupId>cn.hutool</groupId> <artifac

  • MyBatis Properties及别名定义实例详解

    上一篇我们介绍了mybatis的增删改查入门实例,我们发现在 mybatis-configuration.xml 的配置文件中,对数据库的配置都是硬编码在这个xml文件中,如下图,那么我们如何改进这个写法呢? 1.我们将 数据库的配置语句写在 db.properties 文件中 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm jdbc.username=root jdbc.password=ro

  • Mybatis velocity脚本的使用教程详解(推荐)

    可能很多童鞋都还不是很清楚在mybatis可以使用各种脚本语言来定义Mapper文件里面的动态SQL:目前mybatis支持的脚本语言有XML(默认的):Velocity和Freemarker三种.使用不同的脚本语言来完成Mapper文件的编写,第一是使用自己熟悉的脚本语言,第二是能够定义更多丰富的自定义指令来简化Mapper的开发,关于MyBatis支持脚本的原理分析,自定义脚本指令后面再写文章分析,本文先介绍mybatis中velocity脚本的使用方式. mybatis-velocity项

  • Mybatis中注解@MapKey的使用详解

    mybatis的原身是ibatis,现在已经脱离了apache基金会,新官网是http://www.mybatis.org/. 在研究Mybatis源码之前并不知道这个注解的妙用的,但是当我看到参数解析的时候 有这个一个注解,所以我了解了一下,当我们返回像Map<String, Map<String, Object>>这种类型的时候,我们往往很难做到,因为这里面可能是多个表的数据,所以我们不可能再建一个模型. 这时候我们就可以使用这个注解了 @Retention(Retention

  • Spring Boot 2.0多数据源配置方法实例详解

    两个数据库实例,一个负责读,一个负责写. datasource-reader: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://192.168.43.61:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false username: icbc password: icbc driver-class-na

  • Mybatis中Mapper映射文件使用详解

    紧接上文所述,在这篇文章中我将对Mapper映射文件进行详细的说明. Mapper映射文件是一个xml格式文件,必须遵循相应的dtd文件规范,如ibatis-3-mapper.dtd.我们先大体上看看支持哪些配置?如下所示,从Eclipse里截了个屏: 从上图可以看出,映射文件是以<mapper>作为根节点,在根节点中支持9个元素,分别为insert.update.delete.select(增删改查);cache.cache-ref.resultMap.parameterMap.sql. 下

  • Mybatis主配置文件的properties标签详解

    我们配置MYSQL的连接池时可以直接写,也可以从外部导入配置文件. 1.直接在dataSource中写数据库基本信息 <dataSource type="POOLED"> <!-- 配置连接数据库的4个基本信息 --> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value=&

随机推荐