欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-15 12:00:47
mybatis-plus的配置1.maven插件velocity-engine-core是mybatis-plus自动生成代码所依赖的模板(不用自动生成代码功能可不用)

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;
 }
}

参考文档:

数据源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配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: MyBatis-Plus Druid