1. 程式人生 > >Mac下idea從零建立springboot專案以及整合mybatis和mybatis逆向生成工具-springboot(1)

Mac下idea從零建立springboot專案以及整合mybatis和mybatis逆向生成工具-springboot(1)

前言

近期從SSM框架轉為springboot開發restful風格的介面。網路上的資源質量良莠不齊,看了很多部落格,有很多專案名字、專案程式碼、專案id等等等的東西統統一模一樣但是按著來卻是執行不通,我就奇了怪了,你們都是統一思考的麼?

2018-11-28 更新

  • 尋找逆向生成器配置檔案中的classpath方法 跳轉

正文

對於之前有過從事SSM框架或者SSH框架開發的猿來說,springboot會簡單很多,不用那麼繁雜的各種配置檔案,一個helloword專案,可能只需要幾行程式碼而已。
本文將使用jetbrains公司的idea建立springboot專案,並且配置mybatis以及mybatis逆向程式碼生成器

原料及工具

  • jetbrains idea
  • 本地mysql資料庫
  1. url:jdbc:mysql://localhost:3306/hello
  2. user:root
  3. password:Hlm970%&
  4. 資料庫有一張表user

建立springboot專案

idea建立springboot專案真的簡單,新增依賴也是簡單至極。

新建目錄

新建一個空白目錄來存放專案,在desktop建立hellospring目錄。
新建目錄

建立並執行

開啟軟體選擇create a new project,以及spring initializr

,如圖
新建選擇

next 後,填寫相應資訊,這個看個人愛好了,對專案執行沒有多大區別,這裡選擇maven管理工具,當然也可以gradle
填寫資訊
next後就是選擇依賴的介面了,也可以在建立後pom.xml中手動新增。
點選左側web
選擇web
點選左側sql
選擇sql

next 後選擇專案地址
專案地址
finish後等待建立完成。
最終檔案目錄如下:
檔案目錄

ok,現在寫個測試api:
編輯HellospringAplication.java

package com.nick.hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class HellospringApplication {

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

    /**
     * 測試api
     * @return 測試返回字串
     */
	@RequestMapping(value = "/")
    public String index() {
	    return "ok!";
    }
}

修改application.properties

server.port=8080

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/hello?useUnicode=true&characterEncoding=utf-8&nullCatalogMeansCurrent=true
spring.datasource.username=root
spring.datasource.password=Hlm970%&

或者也可以選擇更加簡介的yml檔案進行配置,點選執行:
執行

訪問8080
訪問
一個簡單的api已經可以用了。

配置mybatis 逆向程式碼生成器

新增外掛

修改pom.xml檔案,新增generator外掛

			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
<configuration>
					<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
					<overwrite>true</overwrite>
					<verbose>true</verbose>
						</configuration>
			</plugin>

新建剛剛指定的src/main/resources/generatorConfig.xml,為了便於修改,我是又建了一個generator.properties檔案來儲存屬性

generator.properties

#基本資訊
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/hello?useUnicode=true&characterEncoding=utf-8&nullCatalogMeansCurrent=true
username=root
password=Hlm970%&

#entity 包名和 java目錄
modelPackage=com.nick.hello.entity
modelProject=src/main/java

#sqlmap包名 和resources目錄
sqlPackage=sqlmap
sqlProject=src/main/resources

#mapper包名和 java目錄
mapperPackage=com.nick.hello.dao
mapperProject=src/main/java


table=user

generatorConfig.xml 要把classPathEntry中的location換成自己的。尋找方法

<?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>
    <!--匯入屬性配置 -->
    <properties resource="generator.properties"/>
<!-- 把路徑換成自己的 -->
    <classPathEntry
            location="/Users/hulimin/.m2/repository/mysql/mysql-connector-java/8.0.13/mysql-connector-java-8.0.13.jar" />
    <context id="context1">
        <!-- 註釋 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" /><!-- 是否取消註釋 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成註釋代時間戳 -->
        </commentGenerator>

        <jdbcConnection driverClass="${driver}"
                        connectionURL="${url}"
                        userId="${username}"
                        password="${password}" />

        <!-- 型別轉換 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自動轉化以下型別(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <javaModelGenerator targetPackage="${modelPackage}"
                            targetProject="${modelProject}" />
        <sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}" />
        <javaClientGenerator targetPackage="${mapperPackage}"
                             targetProject="${mapperProject}" type="XMLMAPPER" />

        <!-- 如果需要通配所有表 直接用sql的萬用字元    %即可 -->
        <table schema="" tableName="${table}" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false"
               
        >
            <!--<columnOverride column="REMARKS" javaType="java.lang.String" jdbcType="VARCHAR"/>-->
        </table>

    </context>
</generatorConfiguration>
使用外掛生成程式碼

開啟左側maven project 找到Plugins->mybatis-generator,雙擊mybatis-generator:generator即可。如果沒有這個外掛,重新整理試試.

generator
成功後會生成UserMapper.java User.java UserMapper.xml檔案。在UserMapper新增@Repository註解。有對這6個函式不理解的可以看看這個:
https://blog.csdn.net/babybabyup/article/details/79761618

使用mybatis

程式碼生成後,就可以使用資料庫函數了。
generator.properties中新增mybatis配置

mybatis.mapper-locations=classpath:sqlmap/*.xml

com.nick.hello包中新建services包,實現資料庫介面,新建controller包進行業務邏輯操作。
包

services包中,新建UserService.java,並新增@Service註解.只用insert函式測試一下

package com.nick.hello.services;

import com.nick.hello.dao.UserMapper;
import com.nick.hello.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService implements UserMapper {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int deleteByPrimaryKey(String id) {
        return 0;
    }

    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    public int insertSelective(User record) {
        return 0;
    }

    @Override
    public User selectByPrimaryKey(String id) {
        return null;
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return 0;
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return 0;
    }
}

controller包內新建TestContrller.java

package com.nick.hello.controller;

import com.nick.hello.entity.User;
import com.nick.hello.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class TestController {
    
    @Autowired
    private UserService userService;


    /**
     * 測試用
     * @param name 傳入引數name
     * @param password 傳入引數password
     * @return 插入結果,失敗or成功+id
     */
    @RequestMapping(value = "insert", method = RequestMethod.GET)
    public String insertUser(@RequestParam("name") String name, @RequestParam("password") String password) {

        User user = new User();
        String id = UUID.randomUUID().toString().toLowerCase();
        user.setId(id);
        user.setName(name);
        user.setPassword(password);
        try {
            userService.insert(user);
            return "插入成功,其id為" + id;
        } catch (Exception e) {
            return "插入失敗!";
        }
        
    } 
        
}

最後在HellospringApplication新增mapper掃描註解@MapperScan("com.nick.hello.dao")
執行後測試一下
瀏覽器
資料庫中檢視一下,資料庫

OK了。哈哈哈哈哈啊哈