SpringBoot 實戰 (十三) | 整合 MyBatis (XML 版)

一個優秀的廢人發表於2019-02-28

微信公眾號:一個優秀的廢人 如有問題或建議,請後臺留言,我會盡力解決你的問題。

前言

如題,今天介紹 SpringBoot 與 Mybatis 的整合以及 Mybatis 的使用,之前介紹過了 SpringBoot 整合MyBatis 註解版的使用,上一篇介紹過 MyBatis 的理論,今天這篇就不介紹 MyBatis 的理論了,有興趣的跳轉閱讀:SpringBoot 實戰 (十三) | 整合 MyBatis (註解版)

準備工作

  • SpringBoot 2.1.3
  • IDEA
  • JDK 8

建立表

CREATE TABLE `student`  (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `student_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '學號',
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '姓名',
  `age` int(11) NULL DEFAULT NULL COMMENT '年齡',
  `city` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '所在城市',
  `dormitory` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '宿舍',
  `major` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '專業',
  PRIMARY KEY (`id`) USING BTREE
)ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
複製程式碼

引入依賴

<dependencies>
        <!-- jdbc 連線驅動 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- web 啟動類 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mybatis 依賴 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- druid 資料庫連線池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.14</version>
        </dependency>
        <!-- Mysql 連線類 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
            <scope>runtime</scope>
        </dependency>
        <!-- 分頁外掛 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!-- test 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- springboot maven 外掛 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- mybatis generator 自動生成程式碼外掛 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>
複製程式碼

程式碼解釋很詳細了,但這裡提一嘴,mybatis generator 外掛用於自動生成程式碼,pagehelper 外掛用於物理分頁。

專案配置

server:
  port: 8080

spring:
    datasource:
        name: test
        url: jdbc:mysql://127.0.0.1:3306/test
        username: root
        password: 123456
        #druid相關配置
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

## 該配置節點為獨立的節點,有很多同學容易將這個配置放在spring的節點下,導致配置無法被識別
mybatis:
  mapper-locations: classpath:mapping/*.xml  #注意:一定要對應mapper對映xml檔案的所在路徑
  type-aliases-package: com.nasus.mybatisxml.model  # 注意:對應實體類的路徑

#pagehelper分頁外掛
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
複製程式碼

mybatis generator 配置檔案

這裡要注意,配置 pom.xml 中 generator 外掛所對應的配置檔案時,在 Pom.xml 加入這一句,說明 generator 外掛所對應的配置檔案所對應的配置檔案路徑。這裡已經在 Pom 中配置了,請見上面的 Pom 配置。

${basedir}/src/main/resources/generator/generatorConfig.xml
複製程式碼

generatorConfig.xml :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 資料庫驅動:選擇你的本地硬碟上面的資料庫驅動包-->
    <classPathEntry  location="D:\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--資料庫連結URL,使用者名稱、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/test" userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.nasus.mybatisxml.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>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.nasus.mybatisxml.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是資料庫中的表名或檢視名 domainObjectName是實體類名-->
        <table tableName="student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>
複製程式碼

程式碼註釋很詳細,不多說。

生成程式碼過程

第一步:選擇編輯配置

新增配置

第二步:選擇新增 Maven 配置

選擇 Maven

第三步:新增命令 mybatis-generator:generate -e 點選確定

新增命令

第四步:執行該配置,生成程式碼

特別注意!!!同一張表一定不要執行多次,因為 mapper 的對映檔案中會生成多次的程式碼,導致報錯,切記。如要執行多次,請把上次生成的 mapper 對映檔案程式碼刪除再執行。

執行該配置

第五步:檢查生成結果

生成的程式碼

遇到的問題

請參照別人寫好的遇到問題的解決方法,其中我就遇到資料庫時區不對以及只生成 Insert 方法這兩個問題。都是看以下這篇文章解決的:

Mybatis Generator自動生成程式碼以及可能出現的問題

生成的程式碼

1、實體類:Student.java

package com.nasus.mybatisxml.model;

public class Student {

    private Long id;

    private Integer age;

    private String city;

    private String dormitory;

    private String major;

    private String name;

    private Long studentId;

   // 省略 get 和 set 方法
}
複製程式碼

2、mapper 介面:StudentMapper.java

package com.nasus.mybatisxml.mapper;

import com.nasus.mybatisxml.model.Student;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface StudentMapper {
    int deleteByPrimaryKey(Long id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Long id);

    // 我新增的方法,相應的要在對映檔案中新增此方法
    List<Student> selectStudents();

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}
複製程式碼

3、對映檔案:StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.nasus.mybatisxml.mapper.StudentMapper" >
  <resultMap id="BaseResultMap" type="com.nasus.mybatisxml.model.Student" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="city" property="city" jdbcType="VARCHAR" />
    <result column="dormitory" property="dormitory" jdbcType="VARCHAR" />
    <result column="major" property="major" jdbcType="VARCHAR" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="student_id" property="studentId" jdbcType="BIGINT" />
  </resultMap>

  <sql id="Base_Column_List" >
    id, age, city, dormitory, major, name, student_id
  </sql>

  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from student
    where id = #{id,jdbcType=BIGINT}
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from student
    where id = #{id,jdbcType=BIGINT}
  </delete>

  <insert id="insert" parameterType="com.nasus.mybatisxml.model.Student" >
    insert into student (id, age, city, 
      dormitory, major, name, 
      student_id)
    values (#{id,jdbcType=BIGINT}, #{age,jdbcType=INTEGER}, #{city,jdbcType=VARCHAR}, 
      #{dormitory,jdbcType=VARCHAR}, #{major,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, 
      #{studentId,jdbcType=BIGINT})
  </insert>

  <insert id="insertSelective" parameterType="com.nasus.mybatisxml.model.Student" >
    insert into student
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="age != null" >
        age,
      </if>
      <if test="city != null" >
        city,
      </if>
      <if test="dormitory != null" >
        dormitory,
      </if>
      <if test="major != null" >
        major,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="studentId != null" >
        student_id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=BIGINT},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
      <if test="city != null" >
        #{city,jdbcType=VARCHAR},
      </if>
      <if test="dormitory != null" >
        #{dormitory,jdbcType=VARCHAR},
      </if>
      <if test="major != null" >
        #{major,jdbcType=VARCHAR},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="studentId != null" >
        #{studentId,jdbcType=BIGINT},
      </if>
    </trim>
  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="com.nasus.mybatisxml.model.Student" >
    update student
    <set >
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="city != null" >
        city = #{city,jdbcType=VARCHAR},
      </if>
      <if test="dormitory != null" >
        dormitory = #{dormitory,jdbcType=VARCHAR},
      </if>
      <if test="major != null" >
        major = #{major,jdbcType=VARCHAR},
      </if>
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="studentId != null" >
        student_id = #{studentId,jdbcType=BIGINT},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>

  <update id="updateByPrimaryKey" parameterType="com.nasus.mybatisxml.model.Student" >
    update student
    set age = #{age,jdbcType=INTEGER},
      city = #{city,jdbcType=VARCHAR},
      dormitory = #{dormitory,jdbcType=VARCHAR},
      major = #{major,jdbcType=VARCHAR},
      name = #{name,jdbcType=VARCHAR},
      student_id = #{studentId,jdbcType=BIGINT}
    where id = #{id,jdbcType=BIGINT}
  </update>

  <!-- 我新增的方法 -->
  <select id="selectStudents" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List" />
    from student
  </select>
</mapper>
複製程式碼

serviec 層

1、介面:

public interface StudentService {

    int addStudent(Student student);

    Student findStudentById(Long id);

    PageInfo<Student> findAllStudent(int pageNum, int pageSize);

}
複製程式碼

2、實現類

@Service
public class StudentServiceImpl implements StudentService{

    //會報錯,不影響
    @Resource
    private StudentMapper studentMapper;

    /**
     * 新增學生資訊
     * @param student
     * @return
     */
    @Override
    public int addStudent(Student student) {
        return studentMapper.insert(student);
    }

    /**
     * 根據 id 查詢學生資訊
     * @param id
     * @return
     */
    @Override
    public Student findStudentById(Long id) {
        return studentMapper.selectByPrimaryKey(id);
    }

    /**
     * 查詢所有學生資訊並分頁
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Student> findAllStudent(int pageNum, int pageSize) {
        //將引數傳給這個方法就可以實現物理分頁了,非常簡單。
        PageHelper.startPage(pageNum, pageSize);
        List<Student> studentList = studentMapper.selectStudents();
        PageInfo result = new PageInfo(studentList);
        return result;
    }
}
複製程式碼

controller 層

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/{id}")
    public Student findStidentById(@PathVariable("id") Long id){
        return studentService.findStudentById(id);
    }

    @PostMapping("/add")
    public int insertStudent(@RequestBody Student student){
        return studentService.addStudent(student);
    }

    @GetMapping("/list")
    public PageInfo<Student> findStudentList(@RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize){
        return studentService.findAllStudent(pageNum,pageSize);
    }
}
複製程式碼

啟動類

@SpringBootApplication
@MapperScan("com.nasus.mybatisxml.mapper") // 掃描 mapper 介面,必須加上
public class MybatisxmlApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisxmlApplication.class, args);
    }
}
複製程式碼

提一嘴,@MapperScan("com.nasus.mybatisxml.mappe") 這個註解非常的關鍵,這個對應了專案中 mapper(dao) 所對應的包路徑,必須加上,否則會導致異常。

Postman 測試

1、插入方法:

插入方法結果

2、根據 id 查詢方法:

根據 id 查詢結果

3、分頁查詢方法:

分頁查詢結果

原始碼下載

https://github.com/turoDog/Demo/tree/master/springboot_mybatisxml_demo

幫忙點個 star 可好?

後語

如果本文對你哪怕有一丁點幫助,請幫忙點好看。你的好看是我堅持寫作的動力。

另外,關注之後在傳送 1024 可領取免費學習資料。資料內容詳情請看這篇舊文:Python、C++、Java、Linux、Go、前端、演算法資料分享

一個優秀的廢人

相關文章