SpringBoot+SpringMVC+MybatisPlus框架整合

  • MybatisPlus

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

1、项目结构

2、数据库设计

/*
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');

3、搭建框架

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

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

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

  • 建立成功以后,配置pom.xml文件和application.yml文件web

1.pom.xmlspring

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.tout</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.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>
        <velocity.version>1.7</velocity.version>
        <mybatisplus-spring-boot-starter.version>1.0.1</mybatisplus-spring-boot-starter.version>
        <mybatisplus.version>2.1-gamma</mybatisplus.version>
        <fastjson.version>1.2.31</fastjson.version>
        <mysql-connector-java.version>5.1.38</mysql-connector-java.version>
        <druid.version>1.1.1</druid.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-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>

        <!-- druid阿里巴巴数据库链接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>${velocity.version}</version>
        </dependency>

        <!-- mybatis-plus begin -->
        <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 -->

        <!-- fastjson阿里巴巴jSON处理器 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

2.application.ymlsql

#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

4、mybatis-plus配置-MybatisPlusConfig.java

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

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

###** 5、使用mybatis-plus的代码生成插件**数据库

/**
 * <p>
 * 代码生成器演示
 * </p>
 */
public class MpGenerator {
  /**
   * <p>
   * MySQL 生成演示
   * </p>
   */
  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<String, Object> 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"));
  }

}

执行代码后会生成以下结构:apache

将相应模块代码稍微修改下,放入项目就能够了json

6、代码示例

  • UserMapper.java
/**
 * <p>
  *  Mapper 接口
 * </p>
 *
 * @author Tout-An
 * @since 2017-07-25
 */
public interface UserMapper extends BaseMapper<User> {

}

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

  • UserController.java
/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @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<User> 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<User> 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;
  }

}

7、运行

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

相关文章
相关标签/搜索