1. 程式人生 > >springboot2.0.3快速繼承mybatis圖文分享

springboot2.0.3快速繼承mybatis圖文分享

官網入門

http://www.mybatis.org/mybatis-3/zh/index.html 

目錄

mysql資料庫建立表並插入資料

步驟: 1.建立一個springboot專案: 

 2 修改pom檔案

3、application新增相關配置 

 4 配置mybatis generator 自動生成程式碼外掛

配置pom.xml中generator 外掛所對應的配置檔案

注意 1

注意2 

 自動生成程式碼

 5. SpringBoot啟動類加註解@MapperScan


http://www.mybatis.org/mybatis-3/zh/getting-started.html

https://github.com/mybatis/mybatis-3 

      Spring領域其中最好用的莫過於SpringBoot,感覺很強大的,把以前ssm和ssh的那套整合配置一網打盡,進入主題,直接分享案例搭建全流程。

本專案使用的環境:

開發工具:Intellij IDEA 2018.1.5                                                                                                                                              springboot2.0.3
jdk:1.8.
maven:3.5.2                                                                                                                                                                              mysql8.0.13
額外功能
mybatis generator 自動生成程式碼外掛

mysql資料庫建立表並插入資料

我們先建立一個表user_info(表名不要為user這類容易誤導資料庫的名稱,否則後期generator自動生成程式碼會遇到好多問題) 

 資料庫工具SQLyog  很好用

CREATE TABLE user_info
(
	id BIGINT(20) NOT NULL COMMENT '主鍵ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年齡',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱',
	PRIMARY KEY (id)
);

插入資料 

INSERT INTO user_info (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');

步驟: 
1.建立一個springboot專案: 


 

完成後未改動的pom檔案如下

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

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

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </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>
        </plugins>
    </build>


</project>

 2 修改pom檔案

1 首先咱們建立工程用的sping boot為2.0.7 .從我的截圖和pom檔案上看出

因為筆者建立工程時spring boot包一直拉不下來所以版本改為2.0.3.RELEASE

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

 2 因為我用的mysql為8的版本,所以修改一下mysql的依賴版本

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
            <scope>runtime</scope>
        </dependency>

3 mybatis.generator 外掛

依賴

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>

外掛

           <!-- 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>

完成後重新整理一下pom

工程目錄如下

3、application新增相關配置 

      本案例不使用application.properties檔案 而使用更加簡潔的application.yml檔案。
將resource資料夾下原有的application.properties檔案改為application.yml
(備註:其實SpringBoot底層會把application.yml檔案解析為application.properties), 檔案的內容如下(此處只配置最基本的) 

server:
  port: 8080

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
    username: root
    password: 12345678
mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: com.example.mybatis_demo.po

springboot會自動載入spring.datasource.*相關配置,資料來源就會自動注入到sqlSessionFactory中,sqlSessionFactory會自動注入到Mapper中,對於開發人員不用管,直接拿來使用即可。 

 4 配置mybatis generator 自動生成程式碼外掛

配置pom.xml中generator 外掛所對應的配置檔案

${basedir}/src/main/resources/generator/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="F:\repository\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"/>
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--資料庫連結URL,使用者名稱、密碼 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT" userId="root" password="12345678">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.example.mybatis_demo.po" 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.example.mybatis_demo.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是資料庫中的表名或檢視名 domainObjectName是實體類名-->
        <table tableName="user_info" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

注意 1

generatorConfig.xml的標頭檔案http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd標紅原因:缺少mybatis-generator-core.jar

 https://blog.csdn.net/qq_36688143/article/details/82014889

MyBatis Generator http://www.mybatis.org/generator/index.html 

MyBatis GeneratorXML Configuration File Referencehttp://www.mybatis.org/generator/configreference/xmlconfig.html 

Dependency Information http://www.mybatis.org/generator/dependency-info.html 

注意2 

這裡jdbc連線處的connectionURL為

  <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT" userId="root" password="12345678"> 

而不是 

mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT

主要是因為XML中&為轉義符的原因 

下面是五個在XML檔案中預定義好的實體:

&lt;

<

小於號

&gt;

>

大於號

&amp;

&

&apos;

單引號

&quot;

"

雙引號

實體必須以符號"&"開頭,以符號";"結尾。

注意: 只有"<" 字元和"&"字元對於XML來說是嚴格禁止使用的。剩下的都是合法的,為了減少出錯,使用實體是個好習慣。

https://blog.csdn.net/teedry/article/details/5816687

 

 自動生成程式碼

點選run----> Edit Configurations

 

 

 

 ok

從上往下我依次貼一下自動生成的程式碼

 

public interface UserMapper {
    int deleteByPrimaryKey(Long id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}
public class User {
    private Long id;

    private String name;

    private Integer age;

    private String email;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getAge() {
        return age;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email == null ? null : email.trim();
    }
}

 

<?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.example.mybatis_demo.mapper.UserMapper" >
  <resultMap id="BaseResultMap" type="com.example.mybatis_demo.po.User" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="email" property="email" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, name, age, email
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from user_info
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from user_info
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.example.mybatis_demo.po.User" >
    insert into user_info (id, name, age, 
      email)
    values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, 
      #{email,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.example.mybatis_demo.po.User" >
    insert into user_info
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="age != null" >
        age,
      </if>
      <if test="email != null" >
        email,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=BIGINT},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
      <if test="email != null" >
        #{email,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.mybatis_demo.po.User" >
    update user_info
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="email != null" >
        email = #{email,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.mybatis_demo.po.User" >
    update user_info
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER},
      email = #{email,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>

 

 5. SpringBoot啟動類加註解@MapperScan

@SpringBootApplication
@MapperScan("com.example.mybatis_demo.mapper")
public class MybatisDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisDemoApplication.class, args);
    }
}

 6 測試

就測試一下刪除

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisDemoApplicationTests {

    @Autowired
    private UserMapper userMapper;
    @Test
    public void contextLoads() {
    }

    @Test
    public void testDelete(){
        int i = userMapper.deleteByPrimaryKey((long) 1);
        System.out.println(i);
        assert(i==1);
    }

}

id為1的已經刪除了 

 

教程就到這裡

 

主要參考

https://blog.csdn.net/guobinhui/article/details/79289189

https://blog.csdn.net/winter_chen001/article/details/77249029