從零開始搭建Springboot工程

需求背景分析

在數據庫中存在手機型號的一些信息,根據手機型號找到手機的其他信息,例如手機的歸屬,手機歸屬人的手機號,手機的編號等。

一、創建一個簡單的springboot工程

請參考這篇文章,很簡單,一直下一步就可以了,https://blog.csdn.net/wjg8209/article/details/94546110

二、搭建mysql

1.本地安裝mysql

1、在mysql官網直接,下載mysql,直接安裝上即可
2、這時候用可視化工具鏈接mysql是鏈接不上,需要重置一下密碼
系統偏好設置-mysql
在這裏插入圖片描述
點擊Initialize Database
輸入你的新密碼,記住這個密碼,用於後期鏈接數據庫的登陸使用。
選擇‘Use legacy password‘。
重啓mysql服務。
再用可視化工具去連就OK了

2.創建表和數據庫

1、創建數據庫,不寫了
2、創建表和字段
CREATE TABLEmobile_info(idbigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵id',mobile_novarchar(64) COLLATE utf8mb4_bin NOT NULL COMMENT '設備編號',ownervarchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '手機持有者',modelvarchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '手機型號',create_timetimestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '創建時間',update_timetimestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT '更新時間', PRIMARY KEY (id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT=‘測試機信息表’;

AUTO_INCREMENT=1,主鍵從1開始自增。`
3、創建完後是這樣的
在這裏插入圖片描述

三、springboot整合mybatis

這個章節主要實現springboot和mysql的聯通

項目結構

如圖:
在這裏插入圖片描述

文件特別說明

SptestApplication啓動類,注意加這個註釋哈,@MapperScan (“com.liu.sptest.mapper”),不然會報錯

package com.liu.sptest;

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

@SpringBootApplication
@MapperScan ("com.liu.sptest.mapper")
public class SptestApplication {

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

}

MobileInfo類,與數據庫字段一一對應,@Data註釋可以自動生成get和set方法

package com.liu.sptest.bean;

import lombok.Data;

import java.util.Date;

@Data
public class MobileInfo {
    /**
     * 主鍵
     */
    private Long id;
    /**
     * 設備編號
     */
    private String mobileNo;
    /**
     * 手機持有者
     */
    private String owner;
    /**
     * 持有者手機號
     */
    private String phoneNo;
    /**
     * 手機型號
     */
    private String model;
    /**
     * 創建時間
     */
    private Date createTime;
    /**
     * 更新時間
     */
    private Date updateTime;
}

controller—HelloMissLiu 控制層,儘量輕薄,

package com.liu.sptest.controller;

import com.liu.sptest.common.bean.Result;
import com.liu.sptest.common.enums.CodeMsg;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.liu.sptest.service.MobileInfoService;
import javax.annotation.Resource;

@RestController
@RequestMapping(value = "/beauty")
public class HelloMissLiu {
    @Resource
    private MobileInfoService mobileInfoService;
    @GetMapping(value = "/getMobileInfoByModel")
    public Result getHello(@RequestParam("model") String model) {
        if(model.equals("")){
            return Result.error(CodeMsg.VALIDATION_ERROR);
        }
        return Result.success(mobileInfoService.getMobileInfo(model));

    }
}

mapper.MobileInfoMapper 用來映射真正的mysql語句而抽象出來的接口–非正式定義,就這麼個意思。。。

package com.liu.sptest.mapper;

import org.springframework.stereotype.Repository;
import com.liu.sptest.bean.MobileInfo;
import java.util.List;

@Repository
public interface MobileInfoMapper {
    //增加一條設備信息
    int insertMobileInfo(MobileInfo mobileInfo);

    //修改設備信息
    int updateMobileInfo(String owner);

    //根據型號查詢設備信息
    MobileInfo queryMobileByModel(String model);

    //根據姓名查詢設備信息
    List<MobileInfo> queryMobileByOwner(String owner);
}

MobileInfoService 實現層,主要是業務邏輯的處理

package com.liu.sptest.service;

import com.liu.sptest.mapper.MobileInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.liu.sptest.bean.MobileInfo;

/**
 * @Author: beauty
 * @Date: 2020/4/18 3:00 下午
 */
@Component
public class MobileInfoService {
    @Autowired
    private MobileInfoMapper mobileInfoMapper;

    public MobileInfo getMobileInfo(String model) {
        return mobileInfoMapper.queryMobileByModel(model);

    }

}

MobileInfoMapper.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.liu.sptest.mapper.MobileInfoMapper">

    <resultMap id="BaseResultMap" type="com.liu.sptest.bean.MobileInfo">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="mobile_no" jdbcType="VARCHAR" property="mobileNo" />
        <result column="owner" jdbcType="VARCHAR" property="owner" />
        <result column="phone_no" jdbcType="VARCHAR" property="phoneNo" />
        <result column="model" jdbcType="VARCHAR" property="model" />
        <result column="create_time"  property="createTime" />
        <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
    </resultMap>
    <sql id="Base_Column_List" >
    id, mobile_no, owner, phone_no, model, create_time, update_time
    </sql>

    <select id="queryMobileByModel" parameterType="java.lang.String" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from mobile_infot where model = #{model}
    </select>
</mapper>

application.yml 數據庫的連接信息都在這裏,這裏注意空格,冒號後要有空格,在yml文件中,直到參數名字變色了纔算有效


#數據庫連接:注意要加上時區
server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/tesmobile?serverTimezone=GMT%2B8
    username: root
    password: xxxxx
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.liu.sptest.bean



pom.xml

<?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>org.example</groupId>
    <artifactId>sp_test</artifactId>
    <version>1.0-SNAPSHOT</version>

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

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!-- 加載mybatis整合springboot-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- MySQL的jdbc驅動包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <!--自動生成get和set方法-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.49</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

鏈接數據庫單元測試

下面我們就寫個單測看看有沒有打通mysql,這裏我遇到個問題,就是實體類中字段命名和數據庫設計的不一致時候就取不出來,明明在MobileInfoMapper.xml使用resultMap做了一一映射怎麼會匹配不到呢,後來改了MobileInfoMapper.xml文件,在select語句中加了resultMap=“BaseResultMap”,至於爲什麼這麼幹就可以取出庫裏面所有數據我也不知道,有知道的一定留言告訴我吖,select語句中至少配置resultType和resultMap其中的一個,我之前配置的resultType,後來刪掉了配置了resultMap可以取出所有數據了。

package com.liu.sptest;

import com.alibaba.fastjson.JSON;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.liu.sptest.service.MobileInfoService;
import javax.annotation.Resource;

/**
 * @Author: beauty
 * @Date: 2020/4/23 11:22 上午
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MysqlTest {
    @Resource
    private MobileInfoService mobileInfoService;

    @Test
    public void testMybatis() {
        String str = JSON.toJSONString(mobileInfoService.getMobileInfo("oppo"));
        System.out.println("==================" + str);
    }
}


看下測試結果

在這裏插入圖片描述

四、編寫你要實現的業務邏輯

代碼如上邊的MobileInfoService方法,實現了根據測試機型號查詢測試機信息

五、單元測試

六、 統一封裝返回值Result

具體我是參考https://www.jianshu.com/p/cfd66f651636 這篇文章的,代碼沒有完全複製,取了需要用的部分

創建Result的實體類

該實體類定義了返回結果的基本組成,包括返回的狀態碼,錯誤信息及具體的返回值,而且定義了正常請求時候的返回方法及錯誤請求返回的信息

package com.liu.sptest.common.bean;

import com.liu.sptest.common.enums.CodeMsg;
import lombok.Data;

import java.io.Serializable;

/**
 * @Author: beauty
 * @Date: 2020/4/26 11:06 上午
 */
@Data
public class Result<T> implements Serializable {
    private int code;
    private String msg;
    private T data;

    private Result(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> Result<T> success(T data){
        return  new Result<T>(0,"success",data);
    }

    public static <T> Result<T> error(CodeMsg cm){
        return  new Result<T>(cm.getCode(),cm.getMsg(),null);
    }
}

錯誤信息定義

package com.liu.sptest.common.enums;

import lombok.Data;

/**
 * @Author: beauty
 * @Date: 2020/4/26 11:13 上午
 */
@Data
public class CodeMsg {
    private int code;
    private String msg;

    /**
     * 私有構造器
     * @param code
     * @param msg
     */
    private CodeMsg(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    /**
     * 通用錯誤返回
     */
    public static final CodeMsg SERVER_ERROR = new CodeMsg(60000,"服務器異常!");
    public static final CodeMsg VALIDATION_ERROR = new CodeMsg(60001,"參數效驗錯誤!");
//    public static final CodeMsg BIZ_ERROR = new CodeMsg(60002,"業務異常:%s!");
}

mobileInfoService.getMobileInfo(model)爲一個對象,直接放到success方法中就行了,不要放string,不然返回值格式不好看,而且有反斜槓
return Result.success(mobileInfoService.getMobileInfo(model));

七、看一下效果

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章