1. 程式人生 > >SpringBoot整合Mybatis 以及 mybatis自動生成程式碼配置

SpringBoot整合Mybatis 以及 mybatis自動生成程式碼配置

1、springboot的配置檔案application.yml

#埠
server:
  port: 8080

  #模板頁面
  #註釋的部分是Thymeleaf預設的配置,如有其它需求可以自行更改
  spring:
    thymeleaf:
      cache: false
      prefix: classpath:/templates/
      suffix: .html
      mode: LEGACYHTML5
#      encoding: UTF-8
#      content-type: text/html

##資料來源一
#spring:
#      datasource:
#          driverClass: com.mysql.jdbc.Driver
#          url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
#          username: xuan
#          password: 123456
#資料來源二
spring:
      datasource:
          url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
          username: xuan
          password: 123456
          # 使用druid資料來源
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.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-boot整合mybatis
mybatis:
  #config-location: classpath:/mapper/config/mybatisConfig.xml #可以注射掉,沒用到該配置檔案
  mapper-locations: classpath:/mapper/*Mapper.xml
  #type-aliases-package: com.xuan.entity


2、maven的配置檔案pom.xml (加入springboot整合mybatis的jar包,以及mysql驅動jar包,阿里的資料庫連結池jar包)

以及mybatis 自動生成程式碼的一些配置

<?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.xuan</groupId>
    <artifactId>myspringboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.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>

        <mybatis.generator.version>1.3.2</mybatis.generator.version>
        <mysql.connector.java.version>6.0.6</mysql.connector.java.version>


        <!-- Used by MyBatis Generator to Generate Codes -->
        <!-- 執行命令: mvn mybatis-generator:generate -e -->
        <!--<classPathEntry.mysql.location>${basedir}/target/${project.artifactId}/WEB-INF/lib/mysql-connector-java-${mysql.connector.java.version}.jar</classPathEntry.mysql.location>-->
        <classPathEntry.mysql.location>/Users/chenqixuan/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar</classPathEntry.mysql.location>
        <javaModelGenerator.targetProject>${basedir}/src/main/java</javaModelGenerator.targetProject>
        <sqlMapGenerator.targetProject>${basedir}/src/main/resources</sqlMapGenerator.targetProject>
        <javaClientGenerator.targetProject>${basedir}/src/main/java</javaClientGenerator.targetProject>
        <mybatis.generator.configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</mybatis.generator.configurationFile>
        <mybatis.generator.overwrite>true</mybatis.generator.overwrite>
    </properties>

    <dependencies>
        <!--springboot整合redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--springboot整合mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--mysql jdbc驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.java.version}</version>
        </dependency>
        <!-- alibaba的druid資料庫連線池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.11</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--模板頁面-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <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>${mybatis.generator.version}</version>
            </plugin>
        </plugins>
    </build>


</project>

3、mybatis的配置檔案 (可以不要需要,因為在application.yml配置了)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <!-- changes from the defaults -->
        <setting name="lazyLoadingEnabled" value="false" />
    </settings>

    <mappers>
        <!--在application.yml配置檔案中已經配置的*Mapper.xml,所以這裡不需要重複添加了-->
        <!--<mapper resource="mapper/UserMapper.xml" />-->
    </mappers>

</configuration>

4、使用者實體類xml對映檔案 UserMapper.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.xuan.mapper.UserMapper">

	<!-- 查詢網校的使用者數目 -->
	<select id="getAllUser" resultType="com.xuan.entity.User">
          SELECT * from user
	</select>
	
</mapper>

5、自動生成配置檔案 generatorConfig.xml(專案目錄下執行命令: mvn mybatis-generator:generate -e )

注意:generatorConfig.xml配置檔案中有些引數筆者是配置在pom.xml裡的,另外mysql-connector-java-5.1.38.jar  資料庫mysql驅動也不要使用太高的版本(筆者使用6.0.6版本是遇到錯誤,換成低版本就沒事)

<?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="${classPathEntry.mysql.location}" />

    <context id="mysqlTables" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8"
                        userId="xuan" password="123456">
        </jdbcConnection>

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

        <javaModelGenerator targetPackage="com.xuan.entity"
                            targetProject="${javaModelGenerator.targetProject}">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mapper"
                         targetProject="${sqlMapGenerator.targetProject}">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.xuan.mapper" targetProject="${javaClientGenerator.targetProject}">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!--
        <table tableName="live_course_channel" domainObjectName="LiveCourseChannel"></table>

        -->
        <table tableName="video" domainObjectName="Video"></table>


    </context>
</generatorConfiguration>

6、使用者實體類:
package com.xuan.entity;

import java.io.Serializable;

/**
 * Created by chenqixuan on 17/10/24.
 */
public class User implements Serializable{
    private static final long serialVersionUID = 2120869894112984147L;

    private Integer id;

    private String  name;

    private  Integer age;

    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

7、dao層是使用@Mapper註解介面代理,以前spring是使用自動掃描

package com.xuan.mapper;

import com.xuan.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * Created by chenqixuan on 17/10/24.
 */
@Mapper
public interface UserMapper {

    public List<User> getAllUser();

}

8、controller引用:
package com.xuan.controller;

import com.xuan.entity.User;
import com.xuan.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created by chenqixuan on 17/10/24.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping(value="/all")
    public List<User> getAllUser(){

        return userMapper.getAllUser();
    }


}

9、效果圖:


10、目錄結構: