SpringBoot2.x【四】自動化生成代碼整合Mybatis

SpringBoot2.x【四】自動化生成代碼整合Mybatis

Mybatis 是一個持久層ORM框架,負責(zé)Java與數(shù)據(jù)庫數(shù)據(jù)交互,也可以簡易理解為中介,相對于它,還有個中介是hibernate,不過在mybatis中sql語句的靈活性,可優(yōu)化性比較強,這也是現(xiàn)在大多數(shù)人選擇的原因。

1. mapper.xml、dao接口、實體類自動生成

下載 https://pan.baidu.com/s/1JY7Xduk5E3KPm58AjnueuQ 工具包

image

1.1 修改配置文件generator.xml

解壓之后,這里把文件拷貝到了C:\resources\generator文件夾下,以下稱為"當(dāng)前文件目錄"
一次配置,終身受益

generator.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>
    <!-- 數(shù)據(jù)庫驅(qū)動包位置 也就是剛解壓的文件的位置加上 mysql-connector-java-5.1.34.jar-->
    <classPathEntry location="C:\resources\generator\mysql-connector-java-5.1.34.jar" />
    <!--這里也適用Oracle數(shù)據(jù)庫的自動生成-->
    <!-- <classPathEntry location="C:\resources\generator\ojdbc6.jar" /> -->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 去除生成日期 -->
            <property name="suppressDate" value="true"/>
            <!-- 去除所有的注解 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!-- 數(shù)據(jù)庫鏈接URL、用戶名、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/ceilan" userId="root" password="123456">
        <!-- <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="scott" password="tiger">-->
        </jdbcConnection>
        <!--java類型處理器-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 生成模型的包名和位置 -->
        <javaModelGenerator targetPackage="com.example.entity" targetProject="C:\resources\generator\src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 生成的映射文件包名和位置 -->
        <sqlMapGenerator targetPackage="mapping" targetProject="C:\resources\generator\src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.dao" targetProject="C:\resources\generator\src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 要生成哪個表,更改tableName(數(shù)據(jù)庫里表名)和domainObjectName(實體名,一般首字母大寫)就可以 -->
        <table tableName="area" domainObjectName="Area" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
    </context>
</generatorConfiguration>

1.2 用Java運行自動生成

在當(dāng)前目錄下打開cmd命令,運行如下
注 : windows系統(tǒng)可直接執(zhí)行 [ 生成.bat ] 批處理文件

java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
image

然后把當(dāng)前目錄src下的com文件夾拷貝到項目文件夾下
把mapping文件拷貝到resources文件夾下

image

目錄結(jié)構(gòu)如上

2.集成Mybatis框架

2.1 引入依賴

compile "mysql:mysql-connector-java:5.1.39"
compile 'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.2.0'

2.2 啟動類DemoApplication.java增加掃描配置

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;

@SpringBootApplication
// mapper接口 掃描包配置
@MapperScan(value = "com.example.dao")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

2.3 添加項目首頁index.html

在resources的templates文件中新建index.html

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Welcome SpringBoot</h1>
</body>
</html>

然后在 DemoApplication 啟動類中添加

    //歡迎頁面 首頁
    @RequestMapping("/")
    public String index(){
        return "index";
    }

之前已經(jīng)在application.yml中配置了資源映射設(shè)置,如下

spring: 
  mvc:
    view:
      suffix: .html
  resources:
    static-locations: classpath:/templates

所以現(xiàn)在的項目啟動訪問 http://localhost:8080/ 是可以直接訪問到首頁的

3.添加業(yè)務(wù)層和控制層實現(xiàn)CRUD(增刪改查)

增加業(yè)務(wù)邏輯層包service以及在其下增加impl包用來實現(xiàn)其接口

3.1業(yè)務(wù)邏輯層接口 AreaService.java

package com.example.service;

import com.example.entity.Area;

/**
 * 這里給dao層的代碼拷貝過來先使用
 * created by cfa  2018-11-08 下午 9:56
 **/
public interface AreaService {

    
    int deleteByPrimaryKey(Integer id);

    int insert(Area record);

    int insertSelective(Area record);

    Area selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Area record);

    int updateByPrimaryKey(Area record);
}

3.2業(yè)務(wù)層實現(xiàn)類 AreaServiceImpl.java

package com.example.service.impl;

import com.example.dao.AreaMapper;
import com.example.entity.Area;
import com.example.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * 這里的@Service注解相當(dāng)于自動注冊到Spring的Bean
 * 相當(dāng)于原來的Application.xml里的 <bean id="areaServiceImpl" class="com.example.service.impl.AreaServiceImpl"/>
 * created by cfa  2018-11-08 下午 9:58
 **/
@Service
public class AreaServiceImpl implements AreaService, Serializable {

    private final AreaMapper areaMapper;

    @Autowired
    public AreaServiceImpl(AreaMapper areaMapper) {
        this.areaMapper = areaMapper;
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return areaMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Area record) {
        return areaMapper.insert(record);
    }

    @Override
    public int insertSelective(Area record) {
        return areaMapper.insertSelective(record);
    }

    @Override
    public Area selectByPrimaryKey(Integer id) {
        return areaMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Area record) {
        return areaMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Area record) {
        return areaMapper.updateByPrimaryKey(record);
    }
}

3.3控制層的AreaController.java

package com.example.controller;


import com.example.entity.Area;
import com.example.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("area")
public class AreaController {

    private final AreaService areaService;

    @Autowired
    public AreaController(AreaService areaService) {
        this.areaService = areaService;
    }

    @RequestMapping("query")
    public Area areaList(){
        return areaService.selectByPrimaryKey(1);
    }

}

看到這里,想必看到很多次@Autowired,@Service等注解了,這就是Spring的兩大核心之一的IOC(Inversion of Control),也就是DI依賴注入;
Spring的兩大核心AOP和IOC大家面試的時候也基本都有問到,到這里你IOC就不用頭疼了;

在Spring之前我們寫代碼,用到某個類,我們都需要去new一下,現(xiàn)在有個叫Spring,我把控制權(quán)交給它,OK,然后在給業(yè)務(wù)層蓋上章(加注解),然后讓這個叫Spring的家伙開始工作的時候,交給他去做,控制層需要邏輯A,OK,之前我們已經(jīng)在控制層用DI注入了A,Spring就會把A的調(diào)用給控制層,下面說松緊耦合度,Spring之前,到處寫的都是new新建對象,修改一個類很難,現(xiàn)在隨意修改,只需要蓋個章(DI),讓Spring去管就可以了,你現(xiàn)在要問我原理,那些文鄒鄒的,后續(xù)在研究研究,原理相當(dāng)于文言文,只有研究透了,才能用大家都理解的話寫出來。

業(yè)務(wù)層提供的接口加實現(xiàn)類就是為了實現(xiàn)松耦合,不然一個類就解決了,就像一個手機,壞了,里面的電池,屏幕,主板什么的拆下來還能用,這就是松耦合。

4.熱部署插件

問題1:開發(fā)人員每次修改了一個java文件就需要重啟tomcat,開發(fā)效率很低是不?
答:Jrebel熱部署插件解決你的問題https://mp.weixin.qq.com/s/4Gu5xWWnqtXAoXYDLVmXMA
問題2:你為什么不選擇springboot自帶的熱部署插件
答: 和之前的朋友問我的一樣,問我為啥不把生成代碼的插件放在項目中,一個項目還好,你要是寫了多個項目,一個一個去部署,麻煩不,所以一次配置,一勞永逸。

5.關(guān)于AOP——Spring的又一大核心

面向切面編程(AOP是Aspect Oriented Program的首字母縮寫)我們知道,面向?qū)ο蟮奶攸c是繼承、多態(tài)和封裝.而封裝就要求將功能分散到不同的對象中去,這在軟件設(shè)計中往往稱為職責(zé)分配.實際上也就是說,讓不同的類設(shè)計不同的方法。這樣代碼就分散到一個個的類中去了。這樣做的好處是降低了代碼的復(fù)雜程度,使類可重用.但是人們也發(fā)現(xiàn),在分散代碼的同時,也增加了代碼的重復(fù)性.什么意思呢?比如說,我們在兩個類中,可能都需要在每個方法中做日志。按面向?qū)ο蟮脑O(shè)計方法,我們就必須在兩個類的方法中都加入日志的內(nèi)容。也許他們是完全相同的,但就是因為面向?qū)ο蟮脑O(shè)計讓類與類之間無法聯(lián)系,而不能將這些重復(fù)的代碼統(tǒng)一起來。
也許有人會說,那好辦啊,我們可以將這段代碼寫在一個獨立的類獨立的方法里,然后再在這兩個類中調(diào)用。但是,這樣一來,這兩個類跟我們上面提到的獨立的類就有耦合了,它的改變會影響這兩個類。那么,有沒有什么辦法,能讓我們在需要的時候,隨意地加入代碼呢?這種在運行時,動態(tài)地將代碼切入到類的指定方法、 指定位置上的編程思想就是面向切面的編程。
一般而言,我們管切入到指定類指定方法的代碼片段稱為切面,而切入到哪些類、哪些方法則叫切入點。有了AOP,我們就可以把幾個類共有的代碼,抽取到一個切片中,等到需要時再切入對象中去,從而改變其原有的行為。
這樣看來,AOP其實只是OOP的補充而已。OOP從橫向上區(qū)分出一個個的類來,而AOP則從縱向上向?qū)ο笾屑尤胩囟ǖ拇a。有了AOP,OOP變得立體了。如果加上時間維度,AOP使OOP由原來的二維變?yōu)槿S了,由平面變成立體了。從技術(shù)上來說,AOP基本上是通過代理機制實現(xiàn)的。
AOP在編程歷史上可以說是里程碑式的,對OOP編程是一種十分有益的補充
引自:http://xiaobashagua.iteye.com/blog/1963683你問我為啥排這么緊,哈哈,好東西是留給有耐心的人看的,如果你把這篇文章的IOC和AOP仔細看了,你會對這倆的理解又深了一個層次

5.小敘

本文代碼已上傳Github:https://github.com/cuifuan/springboot-demo
如果你是來學(xué)框架怎么寫CRUD的,我錯了,沒讓你看到具體的,我在寫的是在寫代碼的時候,對插件工具的使用,和了解這些東西的作用,提高開發(fā)效率,并且知道自己用的是什么以及基本原理,而不是僅僅是一個“碼農(nóng)”,謝謝閱覽。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.Struts2.0有幾種標(biāo)簽庫 【參考答案】 UI標(biāo)簽、控制標(biāo)簽、數(shù)據(jù)標(biāo)簽、雜項標(biāo)簽 2.struts2必備包...
    碼記閱讀 1,727評論 0 7
  • 1.JVM 堆內(nèi)存和非堆內(nèi)存 堆和非堆內(nèi)存按照官方的說法:“Java 虛擬機具有一個堆(Heap),堆是運行時數(shù)據(jù)...
    yanzhu728閱讀 1,014評論 0 0
  • 1.StringBuffer與String的區(qū)別 StringBuffer是線程安全的,每次操作字符串,Strin...
    zdd5457閱讀 1,123評論 0 5
  • 做一個令人尊重的人,跟老不老沒有關(guān)系 行為比語言,更能表明心意 不怕疼,不要臉,不怕死,就沒有你拿不下的東西
    guoguoguoguoguo閱讀 135評論 0 0
  • http://www.itdecent.cn/p/a3e1ea5695e7
    QinRenMin閱讀 242評論 0 0

友情鏈接更多精彩內(nèi)容