Spring Boot(三)整合Mybatis

初始準備

本文項目同樣將基於Spring Boot(一)快速開始的項目繼續搭建


項目結構

之前的項目結構如下圖所示
這裏寫圖片描述
本文構建項目目錄結構如下圖所示
其中MybatisGenerator.java是用MyBatis Generator自動生成domain,mapper,以及數據庫sql映射文件
這裏寫圖片描述


配置文件

依賴文件pom.xml

<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>cn.edu.cqu</groupId>
    <artifactId>SpringBootDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</version>
        </dependency>



        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- alibaba的druid數據庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.6</version>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!-- 沒有該配置,devtools 不生效 -->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

依賴配置文件application.yml

這裏使用更簡潔的yml文件配置

server:
  port: 8080

spring:
    datasource:
        name: mysql_test
        type: com.alibaba.druid.pool.DruidDataSource
        #druid相關配置
        druid:
          #監控統計攔截的filters
          filters: stat
          driver-class-name: com.mysql.jdbc.Driver
          #基本屬性
          url: jdbc:mysql://127.0.0.1:3306/testdatabase?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
          username: root
          password: 123456
          #配置初始化大小/最小/最大
          initial-size: 1
          min-idle: 1
          max-active: 20
          #獲取連接等待超時時間
          max-wait: 60000
          #間隔多久進行一次檢測,檢測需要關閉的空閒連接
          time-between-eviction-runs-millis: 60000
          #一個連接在池中最小生存的時間
          min-evictable-idle-time-millis: 300000
          validation-query: SELECT 'x'
          test-while-idle: true
          test-on-borrow: false
          test-on-return: 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
  type-aliases-package: app.domain

自動生成domain,mapper,以及數據庫sql映射文件

使用這個功能首先需要把domain,mapper,把resources文件夾下的mapping文件夾清空。
數據庫表必須先存在,原生的mybatis不能像hibernate一樣自動建表
表結構如下
這裏寫圖片描述
然後創建MyBatis Generator配置文件mybatis-generator-config.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="mysql-connector-java-5.1.25-bin.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:3306/testdatabase" userId="root" password="123456">    
        </jdbcConnection>    
        <javaTypeResolver>    
            <property name="forceBigDecimals" value="false"/>    
        </javaTypeResolver>    
        <!-- 生成模型的包名和位置-->    
        <javaModelGenerator targetPackage="app.domain" 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="app.mapper" targetProject="src/main/java">    
            <property name="enableSubPackages" value="true"/>    
        </javaClientGenerator>    
        <!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名-->    
        <table tableName="info" domainObjectName="BaseInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>  
    </context>    
</generatorConfiguration>    

創建java文件,之後直接運行這個main函數,domain,mapper,以及數據庫sql映射文件都將自動創建出來

package app;

import org.mybatis.generator.api.ShellRunner;

public class MybatisGenerator {

    public static void main(String[] args) {
        args = new String[] { "-configfile", "src\\main\\resources\\mybatis-generator-config.xml", "-overwrite" };
        ShellRunner.main(args);

    }

}

這裏列一下自動生成的代碼。
BaseInfo.java

package app.domain;

public class BaseInfo {
    private Long id;

    private String info;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info == null ? null : info.trim();
    }
}

BaseInfoMapper.java

package app.mapper;

import java.util.List;

import app.domain.BaseInfo;

public interface BaseInfoMapper {
    int deleteByPrimaryKey(Long id);

    int insert(BaseInfo record);

    int insertSelective(BaseInfo record);

    BaseInfo selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(BaseInfo record);

    int updateByPrimaryKey(BaseInfo record);
    //這個是自己添加的方法
    List<BaseInfo> getByInfo(String info);
}

BaseInfoMapper.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="app.mapper.BaseInfoMapper">
  <resultMap id="BaseResultMap" type="app.domain.BaseInfo">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="info" jdbcType="VARCHAR" property="info" />
  </resultMap>
  <sql id="Base_Column_List">
    id, info
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from info
    where id = #{id,jdbcType=BIGINT}
  </select>
  <!-getByInfo這裏是自己寫的方法->
  <select id="getByInfo" parameterType="java.lang.String" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from info
    where info = #{info,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from info
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="app.domain.BaseInfo" useGeneratedKeys="true" keyProperty="id">
    insert into info (id, info)
    values (#{id,jdbcType=BIGINT}, #{info,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="app.domain.BaseInfo">
    insert into info
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="info != null">
        info,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="info != null">
        #{info,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="app.domain.BaseInfo">
    update info
    <set>
      <if test="info != null">
        info = #{info,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="app.domain.BaseInfo">
    update info
    set info = #{info,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>

Service接口和Service實現

Service接口

package app.service;

import java.util.List;

import app.domain.BaseInfo;




public interface SampleService {
    public void addInfo(BaseInfo baseInfo);
    public List<BaseInfo> getByInfo(String info);
}

Service實現

package app.service.Imp;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import app.domain.BaseInfo;
import app.mapper.BaseInfoMapper;
import app.service.SampleService;


@Service
public class SampleServiceImp  implements SampleService{
    @Autowired
    private BaseInfoMapper baseInfoMapper;

    @Override
    @Transactional
    public void addInfo(BaseInfo baseInfo) {
        baseInfoMapper.insert(baseInfo);

    }

    @Override
    @Transactional
    public List<BaseInfo> getByInfo(String info) {
        List<BaseInfo> listInfos = baseInfoMapper.getByInfo(info);
        return listInfos;
    }







}

Controller

SampleController在上一篇文章中已有,本文主要是使用InfoController 的功能,代碼與第二篇是一樣的

package app.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import app.domain.BaseInfo;
import app.mapper.BaseInfoMapper;
import app.service.SampleService;

@RestController
@EnableAutoConfiguration
public class InfoController {
    @Autowired
    private SampleService sampleService;

    @RequestMapping("/addInfo")
    public BaseInfo addInfo(@RequestParam(value = "info")String info) {
        BaseInfo bInfo = new BaseInfo();
        bInfo.setInfo(info);
        sampleService.addInfo(bInfo);
        return bInfo;
    }
    @RequestMapping("/getInfo")
    public List<BaseInfo> getInfo(@RequestParam(value = "info")String info) {
        List<BaseInfo> aBaseInfos = sampleService.getByInfo(info);
        return aBaseInfos;
    }
}

Application啓動應用

這裏需要加入@MapperScan(“app.mapper”)

package app;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("app.mapper")
public class Application {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        SpringApplication.run(Application.class, args);
    }
}

在這個java文件中右鍵 Run as -> Java Application。當看到 “FrameworkServlet ‘dispatcherServlet’: initialization completed in xx ms” 字樣說明啓動成功。
打開瀏覽器訪問 http://localhost:8080/addInfo?info=abc,結果如下:
這裏寫圖片描述
之後訪問http://localhost:8080/getInfo?info=abc可以看到數據已經查詢到了
這裏寫圖片描述

項目可在GitHub上下載https://github.com/tripleHu/SpringBootDemo


項目可能會遇到的問題

  1. 項目啓動時出現org.springframework.beans.factory.UnsatisfiedDependencyException異常,一般情況是無法注入mapper,可以先檢查一遍pom.xml中引入的包的版本之間是否兼容
  2. 有主鍵id爲自動增長的表可以在插入時設置useGeneratedKeys=”true” keyProperty=”id”,可以參照本文中的mapper配置文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章