1. 程式人生 > 實用技巧 >Spring Boot專案開發(一)——通過mybatis-generator自動生成基礎程式碼

Spring Boot專案開發(一)——通過mybatis-generator自動生成基礎程式碼

一、建立專案

通過IDEA的Initializr建立專案,詳情參見:Spring Boot入門

二、新增專案依賴

新增Mybatis、Mysql、mybatis-generator(用於生成專案基礎程式碼)依賴

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"
> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository
--> </parent> <groupId>com.learn</groupId> <artifactId>mall</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mall</name> <description>mall project for Spring Boot</description> <properties> <
java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--新增mybatis依賴--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!--新增MySQL依賴--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!--新增mybatis逆向工程外掛--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build> </project>

三、編寫generatorConfig.xml配置檔案

編寫generatorConfig.xml配置檔案,將檔案放在resources目錄下,配置檔案官網地址:http://mybatis.org/generator/configreference/xmlconfig.html

<?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>
    <!-- 指定資料連線驅動jar地址 -->
    <classPathEntry location="D:\software\apache-maven-3.5.2\repository4\mysql\mysql-connector-java\8.0.18\mysql-connector-java-8.0.18.jar"/>
    <!-- 一個數據庫一個context -->
    <context id="MySQLTables" targetRuntime="MyBatis3">
        <!-- 註釋 -->
        <commentGenerator>
            <!-- 是否取消註釋 -->
            <property name="suppressAllComments" value="true"/>
            <!-- 是否生成註釋代時間戳-->
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <!-- jdbc連線 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.211.128:3316/mall?serverTimeZone=UTC&amp;
                        useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true"
                        userId="root"
                        password="123456"/>
        <!-- 型別轉換 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自動轉化以下型別(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成實體類地址 -->
        <javaModelGenerator targetPackage="com.learn.mall.model.pojo" targetProject="src/main/java">
            <!-- 是否在當前路徑下新加一層schema,eg:fase路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="true"/>
            <!-- 是否針對string型別的欄位在set的時候進行trim呼叫 -->
            <property name="trimStrings" value="true"/>
            <!--建立的model物件是否不可改變,即生成的Model物件不會有setter方法,只有構造方法-->
            <property name="immutable" value="false"/>
        </javaModelGenerator>
        <!-- 生成mapper對映檔案存放位置即xml檔案 -->
        <sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources">
            <!-- 是否在當前路徑下新加一層schema,eg:fase路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成dao類存放位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.learn.mall.model.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <!-- 配置表資訊 -->
        <!--tableName為對應的資料庫表 domainObjectName是要生成的實體類 enable*ByExample
                是否生成 example類   -->
        <table tableName="mall_cart"
               domainObjectName="Cart" enableCountByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
        </table>
        <table tableName="mall_category"
               domainObjectName="Category" enableCountByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
        </table>
        <table tableName="mall_order"
               domainObjectName="Order" enableCountByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
        </table>
        <table tableName="mall_order_item"
               domainObjectName="OrderItem" enableCountByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
        </table>
        <table tableName="mall_product"
               domainObjectName="Product" enableCountByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
        </table>
        <table tableName="mall_user"
               domainObjectName="User" enableCountByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

四、啟動mybatis-generator生成基礎程式碼

開啟IDEA的Maven Projects視窗,點選mybatis-generator啟動外掛,執行完成後即可生成基礎程式碼

注意:程式碼生成之後需要給所有的Mapper檔案加上@Repository註解,否則Service注入時會報錯

package com.learn.mall.model.dao;

import com.learn.mall.model.pojo.Cart;
import org.springframework.stereotype.Repository;

@Repository
public interface CartMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Cart record);

    int insertSelective(Cart record);

    Cart selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Cart record);

    int updateByPrimaryKey(Cart record);
}

五、編寫測試demo

1、在application.properties配置檔案中配置資料庫資訊

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://192.168.211.128:3316\
  /mall?serverTimeZone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
mybatis.mapper-locations=classpath:mappers/*.xml

2、編寫Service層介面

package com.learn.mall.service;

import com.learn.mall.model.pojo.User;

public interface UserService {
    User getUser();
}

3、編寫ServiceImpl

package com.learn.mall.service.impl;

import com.learn.mall.model.dao.UserMapper;
import com.learn.mall.model.pojo.User;
import com.learn.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public User getUser() {
        return userMapper.selectByPrimaryKey(1);
    }
}

4、編寫Controller

package com.learn.mall.controller;

import com.learn.mall.model.pojo.User;
import com.learn.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/test")
    @ResponseBody
    public User getUser(){
        return  userService.getUser();
    }
}

5、瀏覽器請求測試