spring boot 2.1学习笔记【七】SpringBoot 2集成MySQL,Mybatis

springboot系列学习笔记全部文章请移步值博主专栏**: spring boot 2.X/spring cloud Greenwich。
由于是一系列文章,所以后面的文章可能会使用到前面文章的项目。springboot系列代码全部上传至GitHub:https://github.com/liubenlong/springboot2_demo
本系列环境:Java11;springboot 2.1.1.RELEASE;springcloud Greenwich.RELEASE;MySQL 8.0.5;

文章目录

  • 引入依赖
  • 注意事项

上一篇介绍了使用springdataJPA, 这一篇介绍一些mybatis

环境介绍:
MySQL驱动:8.X
使用pagehelper分页
使用druid连接池(1.5.X默认Tomcat连接池,2.X默认是hikari连接池)
使用mybatis-generator插件

引入依赖

我这里使用的都是最新的版本。需要以下依赖:

<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.13version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.3.2version>
        dependency>
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelper-spring-boot-starterartifactId>
            <version>1.2.10version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.10version>
        dependency>

添加mybatis插件:

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring.boot.version}version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
            <plugin>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-maven-pluginartifactId>
                <version>1.3.7version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xmlconfigurationFile>
                    <overwrite>trueoverwrite>
                    <verbose>trueverbose>
                configuration>
            plugin>
        plugins>
    build>

配置druid连接池、mybatis、及pagehelper,参数的含义注释已经写了,更加详细的用法请自行阅读官方文档

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      # 特别注意:java 9以后需要将com.mysql.jdbc.Driver  改为  com.mysql.cj.jdbc.Driver即可
      # 否则报错:Loading class `com.mysql.jdbc.Driver'. This is deprecated.
      driver-class-name: com.mysql.cj.jdbc.Driver
      #基本属性
      url: jdbc:mysql://127.0.0.1:3306/test?charset=utf8mb4&useSSL=false
      username: ****
      password: ****
      #配置初始化大小/最小/最大[仅用于测试,生成环境需要修改哦]
      initial-size: 5
      min-idle: 5
      max-active: 20
      #获取连接等待超时时间
      max-wait: 60000
      #间隔多久进行一次检测,检测需要关闭的空闲连接
      time-between-eviction-runs-millis: 60000
      #一个连接在池中最小生存的时间
      min-evictable-idle-time-millis: 300000
      #指定获取连接时连接校验的sql查询语句
      validation-query: SELECT 'x'
      #验证连接的有效性
      test-while-idle: true
      #获取连接时候验证,会影响性能(不建议true)
      test-on-borrow: false
      #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
      pool-prepared-statements: false
      max-pool-prepared-statement-per-connection-size: 20

mybatis:
  mapper-locations: classpath:mapping/*.xml

#pagehelper
pagehelper:
  helperDialect: mysql
  #  分页参数合理化,默认false禁用 .启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页
  #  用合理化时,如果pageNum<1或pageNum>pages会返回空数据
  reasonable: true
  supportMethodsArguments: true
  # 设置为true时,使用RowBounds分页会进行count查询 .默认=false
  rowBoundsWithCount: true

在src/main/resources/generator目录下新建generatorConfig.xml



<generatorConfiguration>
    
    <classPathEntry location="D:/localRepository/mysql/mysql-connector-java/8.0.13/mysql-connector-java-8.0.13.jar"/>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            
            <property name="suppressAllComments" value="true"/>
        commentGenerator>

        
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/test?charset=utf8mb4&useSSL=false" userId="****"
                        password="****">
        jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>

        
        <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        javaModelGenerator>

        
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        sqlMapGenerator>

        
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        javaClientGenerator>

        
        <table tableName="stu" domainObjectName="Stu" enableCountByExample="true" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="true">table>
    context>
generatorConfiguration>

双击执行mybatis-generator:generate生成mapper及实体类。
spring boot 2.1学习笔记【七】SpringBoot 2集成MySQL,Mybatis_第1张图片
执行完毕后,整个项目目录结构为:
spring boot 2.1学习笔记【七】SpringBoot 2集成MySQL,Mybatis_第2张图片

编写StuService

package com.example.service;

import com.example.mapper.StuMapper;
import com.example.model.Stu;
import com.example.model.StuExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class StuService {
    @Autowired
    private StuMapper stuMapper;

    public List<Stu> findAll(){
        return stuMapper.selectByExample(null);
    }

    public List<Stu> selectByExample(){
        StuExample stuExample = new StuExample();
        stuExample.createCriteria().andAgeEqualTo(12);//条件查询
        stuExample.setOrderByClause("name");//排序
        return stuMapper.selectByExample(stuExample);
    }

    /**
     * PageHelper分页
     * @return
     */
    public PageInfo<Stu> selectByExampleWithPage(int pageNum, int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        StuExample stuExample = new StuExample();
        stuExample.createCriteria().andAgeEqualTo(12);//条件查询
        stuExample.setOrderByClause("name");//排序
        List<Stu> stus = stuMapper.selectByExample(stuExample);
        PageInfo<Stu> pageInfo = new PageInfo<>(stus);
        return pageInfo;
    }

    public int modify(int id , String address){
        Stu stu = stuMapper.selectByPrimaryKey(id);
        stu.setAddress(address);
        return stuMapper.updateByPrimaryKeySelective(stu);
    }
    public int save(){
        Stu stu = new Stu();
        stu.setName("周杰伦");
        stu.setAge(30);
        return stuMapper.insert(stu);
    }
}

编写controller:

package com.example.comtroller;

import com.example.model.Stu;
import com.example.service.StuService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class StuController {
    @Autowired
    private StuService stuService;

    @GetMapping("/findAll")
    public List<Stu> findAll() {
        return stuService.findAll();
    }

    @GetMapping("/selectByExample")
    public List<Stu> selectByExample() {
        return stuService.selectByExample();
    }

    @GetMapping("/selectByExampleWithPage")
    public PageInfo<Stu> selectByExampleWithPage(int pageNum, int pageSize) {
        return stuService.selectByExampleWithPage(pageNum, pageSize);
    }

    /**
     * 测试修改,并且使用restful风格
     *
     * @param id
     * @param address
     * @return
     */
    @PutMapping("/modify/{id}")
    public int modify(@PathVariable("id") int id, @RequestParam("address") String address) {
        return stuService.modify(id, address);
    }

    @GetMapping("/save")
    public int save() {
        return stuService.save();
    }
}

请读者自定运行程序观察结果。

注意事项

generatorConfig.xml下图URL的配置注意xmlbuzhich9i& 需要写成&
在这里插入图片描述

MySQL8.X版本的驱动需要使用com.mysql.cj.jdbc.Driver; 老的com.mysql.jdbc.Driver 废弃了。

springboot系列学习笔记全部文章请移步值博主专栏**: spring boot 2.X/spring cloud Greenwich。
由于是一系列文章,所以后面的文章可能会使用到前面文章的项目。springboot系列代码全部上传至GitHub:https://github.com/liubenlong/springboot2_demo
本系列环境:Java11;springboot 2.1.1.RELEASE;springcloud Greenwich.RELEASE;MySQL 8.0.5;

你可能感兴趣的:(springboot,spring,boot,2.X/spring,cloud,Greenwich)