如何在SpringBoot中使用MybatisPlus

如何在SpringBoot中使用MybatisPlus?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

网站设计、成都网站设计介绍好的网站是理念、设计和技术的结合。成都创新互联公司拥有的网站设计理念、多方位的设计风格、经验丰富的设计团队。提供PC端+手机端网站建设,用营销思维进行网站设计、采用先进技术开源代码、注重用户体验与SEO基础,将技术与创意整合到网站之中,以契合客户的方式做到创意性的视觉化效果。

springboot是什么

springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。

项目目录结构:

如何在SpringBoot中使用MybatisPlus

pom文件:



 4.0.0
 
 com.warrior
 ETH
 1.0-SNAPSHOT
 
 
 
  org.springframework.boot
  spring-boot-starter-parent
  2.0.0.BUILD-SNAPSHOT
 
 
 
 
  
   org.springframework.boot
   spring-boot-starter-web
  
  
  
   com.baomidou
   mybatisplus-spring-boot-starter
   1.0.4
  
 
  
   com.baomidou
   mybatis-plus
   2.0.7
  
  
  
   org.apache.velocity
   velocity
   1.7
  
  
  
   org.freemarker
   freemarker
   2.3.28
  
 
 
  
  
   org.springframework.boot
   spring-boot-starter-jdbc
  
  
  
   mysql
   mysql-connector-java
  
  
  
   com.alibaba
   druid
   1.1.9
  
  
  
   org.projectlombok
   lombok
   0.10.1
   provided
  
 
 
 
 
 
  
   
    org.springframework.boot
    spring-boot-maven-plugin
   
  
 
 
 
 
 
  
   spring-snapshots
   http://repo.spring.io/snapshot
   
    true
   
  
  
   spring-milestones
   http://repo.spring.io/milestone
  
 
 
  
   spring-snapshots
   http://repo.spring.io/snapshot
  
  
   spring-milestones
   http://repo.spring.io/milestone
  
 

Application

package com.warrior;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
@SpringBootApplication
@MapperScan("com.warrior.mapper") //配置mapper扫描
public class Application {
 
 public static void main(String[] args) throws Exception {
  SpringApplication.run(Application.class, args);
 }
}

application.properties

#默认启用开发环境配置
spring.profiles.active=dev
#启用生产环境配置
#spring.profiles.active=pro

application-dev.properties

server.port=8080
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/eth
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis-plus.typeAliasesPackage=com.cn.restyle.entity

配置文件:

1).

package com.warrior.config;
 
import javax.sql.DataSource; 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
 
import com.alibaba.druid.pool.DruidDataSource;
 
/**
 * 数据源配置
 */
@Configuration
public class DataSourceConfig {
 
 @Bean(name="dataSource")
 @ConfigurationProperties(prefix="spring.datasource")
 public DataSource dataSource(){
  return new DruidDataSource();
 }
 
 // 配置事物管理器
 @Bean(name="transactionManager")
 public DataSourceTransactionManager transactionManager(){
  return new DataSourceTransactionManager(dataSource());
 }
 
}

2). MybatisPlusConfig.java:

package com.warrior.config;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
 
@Configuration
//扫描dao或者是Mapper接口
@MapperScan("com.warrior.mapper*")
public class MybatisPlusConfig {
 /**
  * mybatis-plus 分页插件
  */
 
 @Bean
 public PaginationInterceptor paginationInterceptor(){
  PaginationInterceptor page = new PaginationInterceptor();
  page.setDialectType("mysql");
  return page;
 } 
}

生成代码:

1).mysql数据库建表

如何在SpringBoot中使用MybatisPlus

2).代码生成器MpGenenator.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 
/**
 * 

 * 代码生成器演示  * 

 */ public class MpGenerator {    final static String dirPath = "D://";    /**   * 

  * MySQL 生成演示   * 

  */  public static void main(String[] args) {   AutoGenerator mpg = new AutoGenerator();   // 选择 freemarker 引擎,默认 Veloctiy   //mpg.setTemplateEngine(new FreemarkerTemplateEngine());     // 全局配置   GlobalConfig gc = new GlobalConfig();   gc.setOutputDir(dirPath);   gc.setAuthor("lqh");   gc.setFileOverride(true); //是否覆盖   gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false   gc.setEnableCache(false);// XML 二级缓存   gc.setBaseResultMap(true);// XML ResultMap   gc.setBaseColumnList(true);// XML columList     // 自定义文件命名,注意 %s 会自动填充表实体属性!   // gc.setMapperName("%sDao");   // gc.setXmlName("%sMapper");   // gc.setServiceName("MP%sService");   // gc.setServiceImplName("%sServiceDiy");   // gc.setControllerName("%sAction");   mpg.setGlobalConfig(gc);     // 数据源配置   DataSourceConfig dsc = new DataSourceConfig();   dsc.setDbType(DbType.MYSQL);   dsc.setTypeConvert(new MySqlTypeConvert(){    // 自定义数据库表字段类型转换【可选】    @Override    public DbColumnType processTypeConvert(String fieldType) {     System.out.println("转换类型:" + fieldType);     // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。     return super.processTypeConvert(fieldType);    }   });   dsc.setDriverName("com.mysql.jdbc.Driver");   dsc.setUsername("root");   dsc.setPassword("123456");   dsc.setUrl("jdbc:mysql://127.0.0.1:3306/eth?characterEncoding=utf8");   mpg.setDataSource(dsc);     // 策略配置   StrategyConfig strategy = new StrategyConfig();   // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意   strategy.setTablePrefix(new String[] { "tb_", "tsys_" });// 此处可以修改为您的表前缀   strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略   // strategy.setInclude(new String[] { "user" }); // 需要生成的表   // strategy.setExclude(new String[]{"test"}); // 排除生成的表   // 自定义实体父类   // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");   // 自定义实体,公共字段   // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });   // 自定义 mapper 父类   // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");   // 自定义 service 父类   // strategy.setSuperServiceClass("com.baomidou.demo.TestService");   // 自定义 service 实现类父类   // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");   // 自定义 controller 父类   // strategy.setSuperControllerClass("com.baomidou.demo.TestController");   // 【实体】是否生成字段常量(默认 false)   // public static final String ID = "test_id";   // strategy.setEntityColumnConstant(true);   // 【实体】是否为构建者模型(默认 false)   // public User setName(String name) {this.name = name; return this;}    strategy.setEntityBuilderModel(true);   mpg.setStrategy(strategy);     // 包配置   PackageConfig pc = new PackageConfig();   pc.setParent("com");   pc.setModuleName("warrior");   pc.setController("controler");   pc.setEntity("entity");   pc.setMapper("mapper");   pc.setService("service");   pc.setServiceImpl("serviceImpl");   pc.setXml("mapperXml");     mpg.setPackageInfo(pc);     // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】   InjectionConfig cfg = new InjectionConfig() {    @Override    public void initMap() {     Map map = new HashMap();     map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");     this.setMap(map);    }   };     // 自定义 xxList.jsp 生成   List focList = new ArrayList(); /*  focList.add(new FileOutConfig("/template/list.jsp.vm") {    @Override    public String outputFile(TableInfo tableInfo) {     // 自定义输入文件名称     return "D://my_" + tableInfo.getEntityName() + ".jsp";    }   });   cfg.setFileOutConfigList(focList);   mpg.setCfg(cfg);*/     // 调整 xml 生成目录演示 /*  focList.add(new FileOutConfig("/templates/mapper.xml.vm") {    @Override    public String outputFile(TableInfo tableInfo) {     return dirPath + tableInfo.getEntityName() + "Mapper.xml";    }   });   cfg.setFileOutConfigList(focList);   */   mpg.setCfg(cfg);     // 关闭默认 xml 生成,调整生成 至 根目录 /*  TemplateConfig tc = new TemplateConfig();   tc.setXml(null);   mpg.setTemplate(tc);*/     // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,   // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称   // TemplateConfig tc = new TemplateConfig();   // tc.setController("...");   // tc.setEntity("...");   // tc.setMapper("...");   // tc.setXml("...");   // tc.setService("...");   // tc.setServiceImpl("...");   // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。   // mpg.setTemplate(tc);     // 执行生成   mpg.execute();     // 打印注入设置【可无】   System.err.println(mpg.getCfg().getMap().get("abc"));  }  }

生成的文件如下,只要将对应文件拷到项目对应包即可:

如何在SpringBoot中使用MybatisPlus

下面把对应类展示出来:

.entity-->Student.java

package com.warrior.entity;
 
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
 
/**
 * 

 *   * 

 *  * @author lqh  * @since 2018-05-25  */ @TableName("tb_student") public class Student extends Model {    private static final long serialVersionUID = 1L;   @TableId(value="id", type= IdType.AUTO) private Integer id; @TableField("stu_name") private String stuName; @TableField("stu_number") private String stuNumber; private Integer age;     public Integer getId() { return id; }   public Student setId(Integer id) { this.id = id; return this; }   public String getStuName() { return stuName; }   public Student setStuName(String stuName) { this.stuName = stuName; return this; }   public String getStuNumber() { return stuNumber; }   public Student setStuNumber(String stuNumber) { this.stuNumber = stuNumber; return this; }   public Integer getAge() { return age; }   public Student setAge(Integer age) { this.age = age; return this; }   @Override protected Serializable pkVal() { return this.id; }   }

.mapper-->StudentMapper.java

package com.warrior.mapper;
 
import com.warrior.entity.Student;
import com.baomidou.mybatisplus.mapper.BaseMapper;
 
/**
 * 

 * Mapper 接口  * 

 *  * @author lqh  * @since 2018-05-25  */ public interface StudentMapper extends BaseMapper {   }

mapperXml-->StudentMapper.xml(这个文件要放到src/main/resources/mapper)




 
	
	
		
		
		
		
	
 
 
 
  id, stu_name AS stuName, stu_number AS stuNumber, age
 
 

.service-->IStudentService.java

package com.warrior.service;
 
import com.warrior.entity.Student;
import com.baomidou.mybatisplus.service.IService;
 
/**
 * 

 * 服务类  * 

 *  * @author lqh  * @since 2018-05-25  */ public interface IStudentService extends IService { }

.serviceImpl-->StudentServiceImpl.java

package com.warrior.serviceImpl;
 
import com.warrior.entity.Student;
import com.warrior.mapper.StudentMapper;
import com.warrior.service.IStudentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
 
/**
 * 

 * 服务实现类  * 

 *  * @author lqh  * @since 2018-05-25  */ @Service public class StudentServiceImpl extends ServiceImpl implements IStudentService { }

.controler-->StudentController.java 

package com.warrior.controler;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
/**
 * 

 * 前端控制器  * 

 *  * @author lqh  * @since 2018-05-25  */ @Controller @RequestMapping("/warrior/student") public class StudentController { }

经过以上六步项目已经搭建完成,下面就是写业务代码了,只需要实现controller即可,下面对StudentController.java进行修改:

package com.warrior.controler;
 
import com.warrior.entity.Student;
import com.warrior.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
/**
 * 

 * 前端控制器  * 

 *  * @author lqh  * @since 2018-05-05  */ @Controller @RequestMapping("/warrior/student") public class StudentController {  @Autowired  IStudentService iStudentService;    @RequestMapping("/hello")  @ResponseBody  public String hello() {   //insert   Student student = new Student()     .setStuName("zhangsan")     .setStuNumber("54")     .setAge(23);   boolean res = iStudentService.insert(student);     return res ? "success" : "fail";  } }

看完上述内容,你们掌握如何在SpringBoot中使用MybatisPlus的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


文章题目:如何在SpringBoot中使用MybatisPlus
文章源于:http://bzwzjz.com/article/pigjoo.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 营销网站建设 手机网站制作 成都企业网站制作 成都网站建设 成都网站设计 企业网站设计 响应式网站建设 自适应网站设计 成都网站建设公司 网站设计制作 移动手机网站制作 成都网站建设 企业网站设计 成都网站建设公司 外贸网站设计方案 成都网站建设 成都网站设计公司 网站制作 网站设计制作报价 成都品牌网站设计 网站建设推广 上市集团网站建设