SpringBoot+SpringMVC+MybatisPlus框架整合

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

  • MybatisPlus

这是一个mybatis的增强工具包,好处请大家自行去官方文档查阅,这里就不再赘述了。文档链接:http://mp.baomidou.com/#/?id=%e7%ae%80%e4%bb%8b

一、项目结构

SpringBoot+SpringMVC+MybatisPlus框架整合_第1张图片

二、数据库设计

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50716
Source Host           : localhost:3306
Source Database       : demo

Target Server Type    : MYSQL
Target Server Version : 50716
File Encoding         : 65001

Date: 2017-07-25 16:21:58
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(10) NOT NULL COMMENT '主键ID',
  `name` varchar(30) DEFAULT NULL COMMENT '名称',
  `age` int(11) DEFAULT NULL COMMENT '年龄',
  `phone` varchar(11) DEFAULT NULL COMMENT '手机号码',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '张三', '17', '12345678');
INSERT INTO `user` VALUES ('2', '李四', '17', '12345678');
INSERT INTO `user` VALUES ('3', '王五', '17', '12345678');

三、搭建框架

  • 这个Spring Boot我是通过IntelliJ IDEA快速搭建的

IntelliJ IDEA是非常流行的IDE,IntelliJ IDEA 从14.1已经支持Spring Boot了。

  • 在File菜单里面选择 New > Project,然后选择Spring Initializr,接着一步步操作即可,很方便。

  • 创建成功之后,配置pom.xml文件和application.yml文件

1.pom.xml



    4.0.0

    com.tout
    demo
    0.0.1-SNAPSHOT
    war

    demo
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        1.7
        1.0.1
        2.1-gamma
        1.2.31
        5.1.38
        1.1.1

    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        


        
            mysql
            mysql-connector-java
            ${mysql-connector-java.version}
        

        
        
            com.alibaba
            druid
            ${druid.version}
        

        
        
            org.apache.velocity
            velocity
            ${velocity.version}
        

        
        
            com.baomidou
            mybatisplus-spring-boot-starter
            ${mybatisplus-spring-boot-starter.version}
        

        
            com.baomidou
            mybatis-plus
            ${mybatisplus.version}
        
        

        
        
            com.alibaba
            fastjson
            ${fastjson.version}
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    




2.application.yml

#server
server:
  address: 192.168.3.77
  context-path: /demo/
  port: 9090
  session-timeout: 30
  tomcat.max-threads: 0
  tomcat.uri-encoding: UTF-8
  error:
    path: /error

#jdbc_config
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf8
    username: root
    password: 123456
    driverClassName: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #druid_config
    validation-query: "SELECT 'X' FROM DUAL"
    max-wait: 10000 #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制
    max-idle: 10 #最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被释放。设为0表示无限制
    min-idle: 5  ##最小空闲连接:连接池中容许保持空闲状态的最小连接数量,低于这个数量将创建新的连接
    max_active: 50   ##连接池的最大数据库连接数。设为0表示无限制
    initial-size: 5  #初始化连接:连接池启动时创建的初始化连接数量
    test-on-borrow: false
    test-while-idle: true
    remove_abandoned: true #超过removeAbandonedTimeout时间后,是否进 行没用连接(废弃)的回收(默认为false,调整为true)
    remove_abandoned_timeout: 180 #超过时间限制,回收没有用(废弃)的连接(默认为 300秒,调整为180)
    time-between-eviction-runs-millis: 18800
    pool-prepared-statements: true
    max-pool-prepared-statement-per-connection-size: 20
    connection-properties: config.decrypt=true;druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    filters: stat,wall,log4j2

#view
  mvc:
    view:
      prefix: /WEB-INF/view/
      suffix: .jsp

#mybatis
mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  typeAliasesPackage: com.tout.demo.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 2
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    #序列接口实现类配置
    #key-generator: com.tout.demo.xxx
    #逻辑删除配置
    #logic-delete-value: 0
    #logic-not-delete-value: 1
    #自定义填充策略接口实现
    #meta-object-handler: com.tout.demo.xxx
    #自定义SQL注入器
    #sql-injector: com.tout.demo.xxx
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false

#logging
logging:
  level: warn
  file: ./logs/spring-boot-logging.log


四、mybatis-plus配置-MybatisPlusConfig.java

@Configuration
@MapperScan("com.tout.demo.mapper*")
public class MybatisPlusConfig {

  /**
   * mybatis-plus分页插件
*/ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }

###** 五、使用mybatis-plus的代码生成插件**

/**
 * 

* 代码生成器演示 *

*/ public class MpGenerator { /** *

* MySQL 生成演示 *

*/ public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir("D://"); gc.setFileOverride(true); gc.setActiveRecord(true); gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(false);// XML columList gc.setAuthor("Tout-An"); // 自定义文件命名,注意 %s 会自动填充表实体属性! // gc.setMapperName("%sDao"); // gc.setXmlName("%sDao"); // 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/demo?characterEncoding=utf8"); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意 // strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 strategy.setInclude(new String[] { "user" }); // 需要生成的表 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 // 自定义实体父类 // strategy.setSuperEntityClass("com.tout.demo.TestEntity"); // 自定义实体,公共字段 // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); // 自定义 mapper 父类 // strategy.setSuperMapperClass("com.tout.demo.TestMapper"); // 自定义 service 父类 // strategy.setSuperServiceClass("com.tout.demo.TestService"); // 自定义 service 实现类父类 // strategy.setSuperServiceImplClass("com.tout.demo.TestServiceImpl"); // 自定义 controller 父类 // strategy.setSuperControllerClass("com.tout.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("tout"); 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); } }; mpg.setCfg(cfg); // 自定义模板配置,可以 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+SpringMVC+MybatisPlus框架整合_第2张图片

将相应模块代码稍微修改下,放入项目就可以了

六、代码示例

  • UserMapper.java
/**
 * 

* Mapper 接口 *

* * @author Tout-An * @since 2017-07-25 */ public interface UserMapper extends BaseMapper { }

打开你会发现mapper里面是空的,那是因为mybatis-plus已经帮我们把一些常用的通用的增删改查的代码,还有对分页查询的处理全都封装在BaseMapper里了,简化了我们的开发代码量。

SpringBoot+SpringMVC+MybatisPlus框架整合_第3张图片

  • UserController.java
/**
 * 

* 前端控制器 *

* * @author Tout-An * @since 2017-07-25 */ @RestController @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; /** * 分页 PAGE */ @GetMapping("/list")//等同于@RequestMapping(value = "/list",method = RequestMethod.GET) public Page list() { return userService.selectPage(new Page<>(0, 12)); } /** * 添加 */ @PostMapping("/add") public Object add() { User user = new User(1, "张三", 17, "12345678"); JSONObject result = new JSONObject(); result.put("result", userService.insert(user)); return result; } /** * 删除 */ @PostMapping("/del") public Object del() { JSONObject result = new JSONObject(); result.put("result", userService.deleteById(1)); return result; } /** * 更新 */ @PostMapping("/upd") public Object upd() { User user = new User(1, "张三1", 17, "12345678"); JSONObject result = new JSONObject(); result.put("result", userService.insertOrUpdate(user)); return result; } /** * 查询 */ @GetMapping("/query") public Object query() { JSONObject result = new JSONObject(); result.put("result", userService.selectById(1)); return result; } /** * 添加 */ @PostMapping("/addBatch") public Object addBatch() { List list = new ArrayList<>(); User user = new User(2, "李四", 17, "12345678"); list.add(user); user = new User(3, "王五", 17, "12345678"); list.add(user); JSONObject result = new JSONObject(); result.put("result", userService.insertBatch(list)); return result; } }

七、运行

直接运行Application.java启动项目,项目会运行在springboot内嵌的web容器中。

SpringBoot+SpringMVC+MybatisPlus框架整合_第4张图片

转载于:https://my.oschina.net/u/2963821/blog/1487224

你可能感兴趣的:(SpringBoot+SpringMVC+MybatisPlus框架整合)