Spring Boot學(xué)習(xí)筆記(五)整合MyBatis實現(xiàn)數(shù)據(jù)庫訪問

本文主要在上一篇[Spring Boot學(xué)習(xí)筆記(四)構(gòu)建RESTful API標準工程實例]的基礎(chǔ)上,整合MyBatis,實現(xiàn)簡單的MySql數(shù)據(jù)庫訪問

引入依賴

這里主要依賴兩個,一個是連接MySql的mysql-connector-java,還一個是SpringBoot整合MyBatis的核心依賴mybatis-spring-boot-starter

可以從maven倉庫里生成對應(yīng)的配置代碼:

圖1

對應(yīng)pom.xml如下:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>

配置數(shù)據(jù)庫

自己安裝下MySql,創(chuàng)建庫和表,我這邊demo的表如下:

CREATE TABLE `temp` (
    `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '自增長id',
    `name` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '姓名',
    `content` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '描述',
    PRIMARY KEY (`id`)
)
COMMENT='測試表';

application.properties下配置對應(yīng)的數(shù)據(jù)庫地址:

spring.datasource.url=jdbc:mysql://localhost:3306/mytest
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

實際代碼編寫

首先創(chuàng)建數(shù)據(jù)庫映射對象Temp:

public class Temp {
    
    private Integer id;
    private  String name;
    private String content;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setId(String name) {
        this.name = name;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

然后創(chuàng)建Temp映射的操作TempMapper:

@Mapper
public interface TempMapper {

    @Select("SELECT * FROM TEMP WHERE ID = #{id}")
    Temp findById(@Param("id") Integer id);

    @Insert("INSERT INTO TEMP(NAME, CONTENT) VALUES(#{name}, #{content})")
    int insert(Temp temp);

    @Update("UPDATE TEMP SET  CONTENT=#{content} WHERE ID=#{id}")
    int update(@Param("content") String content, @Param("id") Integer id);
}

編寫對應(yīng)的service層TempServiceImpl,TempService:

public interface TempService {
    public Temp getTemp(Integer id);
    public Boolean insertTemp(Temp entity);
    public Boolean updateTemp(Temp entity);
}
@Service
public class TempServiceImpl implements TempService{

    @Autowired
    private TempMapper tempMapper;

    @Override
    public Temp getTemp(Integer id)
    {
        return tempMapper.findById(id);
    }

    @Override
    public Boolean insertTemp(Temp entity)
    {
        return tempMapper.insert(entity)>0;
    }

    @Override
    public Boolean updateTemp(Temp entity)
    {
        return tempMapper.update(entity.getContent(),entity.getId())>0;
    }
}

最后編寫Controller:

@RestController
public class TempController {
    @Autowired
    private TempService tempService;

    @ApiOperation(value="MyBatis_Demo", notes="MyBatis實現(xiàn)數(shù)據(jù)庫訪問demo")
    @RequestMapping(value = "/temp",method = RequestMethod.GET)
    public Temp getTemp()
    {
        Temp t=tempService.getTemp(1);
        return t;
    }
}

好啦,大功告成,如果沒有意外的話,應(yīng)該能順利看到結(jié)果啦。

圖2

問題匯總

編寫過程中不是一帆風(fēng)順的,我遇到的問題如下,供大家參考。

問題1

啟動時提示Failed to start connecter[HTTP/1.1-8080]

圖3
圖4

看到這個提示后還是比較好定位問題的,基本鎖定端口被占用了,很好奇被誰占用了,于是排查了下:

打開命令窗口輸入:

netstat -aon|findstr "8080"

圖5

找到對應(yīng)的PID后到任務(wù)管理器去查看被什么進程給占用了

圖6

結(jié)果發(fā)現(xiàn)是個奇怪的進程,后來百度了下和docker有關(guān),這才恍然大悟,之前在docker下調(diào)試 .net core項目的。關(guān)閉進程問題順利解決。

問題2

Consider defining a bean of type 'com.example.api_demo.domain.repository.TempMapper' in your configuration.

這個自己犯了錯誤,忘記在啟動類配置掃描包了,立馬添加上。

圖7
問題3

The server time zone value '?泄???????' is unrecognized or represents more t...

也是一個奇葩的問題,百度一下,原來碰到的人挺多,原因就是高版本的MySql驅(qū)動會有數(shù)據(jù)庫和系統(tǒng)時區(qū)差異,我用的版本是6.0.6,所以碰到了,修改下配置,執(zhí)行時區(qū)就可以了

jdbc:mysql://localhost:3306/mytest?serverTimezone=UTC

或者用回5.1.4版本,該版本不會存在時區(qū)問題。

問題4

Could not autowired,No beans of '****' type found

圖8

這個問題困擾了我一陣,很尷尬,應(yīng)該早點百度的或者先嘗試一下編譯的,后來發(fā)現(xiàn)編譯能通過,運行也沒問題,后來才知道,可參考這篇博客

如果不想看到這個報錯,可降低Autowired檢測的級別:


圖9

總結(jié)

到這里,簡單MyBatis實現(xiàn)數(shù)據(jù)庫訪問已經(jīng)基本實現(xiàn),但這不能滿足實際業(yè)務(wù)需求,比如復(fù)雜的sql如何處理,如何訪問多個庫等。

同時,MyBatis的一些注解對于新手來說還是比較陌生的,下一篇我會嘗試從我的角度去深度整理下MyBatis的復(fù)雜使用,和大家一起分享,共同進步。

?著作權(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)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,680評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,284評論 6 342
  • 1. 簡介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的...
    笨鳥慢飛閱讀 6,274評論 0 4
  • 都說"陪伴是最長情的告白"。春節(jié)假期里,我終于整天有時間陪在孩子左右。傾聽他的新年新愿,檢查指導(dǎo)一下他的作業(yè)情況。
    花草呢喃閱讀 303評論 0 0
  • 過年的意義 PS 我是一個留守兒童,一年就見爸媽一次,過年對于我來說就像是親友會面。 講述正題 春節(jié)是中國...
    pattern_eb3b閱讀 131評論 0 0

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