第四篇:SpringBoot 2.x整合MyBatis

用完spring-data-jpa之后并不是很想用mybatis,但是沒辦法呀混驰,大環(huán)境還是mybatis,而且現(xiàn)在mybatis也出了不少插件耕蝉,我們還是一起看看如何整合mybatis吧
關(guān)于整合mybatis有兩種方式,一種是注解方式,另一種是傳統(tǒng)的xml方式

注解方式

先看看引入的依賴

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

sql文件

CREATE TABLE `test`.`Untitled`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `passwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///test?useSSL=true
spring.datasource.username=root
spring.datasource.password=root

#打印sql語句到控制臺(tái)
logging.level.com.priv.gabriel.demoformybatis.mapper=debug

User.java

package com.priv.gabriel.demoformybatis.entity;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-14
 * @Description:
 */
public class User {

    private long id;

    private String username;

    private String passwd;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
}

UserMapper.java

package com.priv.gabriel.demoformybatis.mapper;

import com.priv.gabriel.demoformybatis.entity.User;
import org.apache.ibatis.annotations.*;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-14
 * @Description:
 */
@Mapper
public interface UserMapper {

    /*注解方式的話直接在方法上寫上對應(yīng)的sql語句就可以了*/
    @Select("select * from user where id = #{id}")
    /*如果需要重復(fù)使用該Result,給該Results加一個(gè) id 屬性砰碴,下面即可使用@ResultMap(id)重復(fù)調(diào)用*/
    @Results(id = "user",value = {
            @Result(property = "username",column = "name")
    })
    User findById(long id);

    /*獲取回傳自增id*/
    /*id會(huì)自動(dòng)存入user中*/
    @Insert("insert into user(name,passwd) values (#{username},#{passwd})")
    @Options(useGeneratedKeys = true,keyProperty = "id")
    int inertUser(User user);
}

UserController.java

package com.priv.gabriel.demoformybatis.controller;

import com.priv.gabriel.demoformybatis.entity.User;
import com.priv.gabriel.demoformybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-14
 * @Description:
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public User selectById(@PathVariable long id){
        return userMapper.findById(id);
    }

    @RequestMapping(value = {""},method = RequestMethod.POST)
    public String addUser(User user){
        userMapper.inertUser(user);
        return "現(xiàn)在自增id為"+user.getId();
    }
}

在SpringBoot1.x中還需要在啟動(dòng)類中加入@MapperScan("mapper所在目錄"),而在2.x版本中不需要加入就可以自動(dòng)掃描到mapper了

加入分頁

需要引入pageHelper依賴

        <!-- 引入分頁插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

在UserMapper中新增一個(gè)查詢所有信息的方法

    @Select("select * from user")
    /*調(diào)用之前的Results*/
    @ResultMap("user")
    List<User> listUser();

在Controller中調(diào)用

    /*獲取分頁數(shù)據(jù) 包含分頁詳細(xì)信息*/
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public PageInfo getAll(@RequestParam Integer page, @RequestParam Integer size){
        PageHelper.startPage(page,size);
        List<User> users = userMapper.listUser();
        PageInfo<User> pageInfo = new PageInfo(users);
        return pageInfo;
    }

    /*僅獲取分頁數(shù)據(jù)
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public List<User> getAll(@RequestParam Integer page, @RequestParam Integer size){
        PageHelper.startPage(page,size);
        List<User> users = userMapper.listUser();
        return users;
    }*/

XML方式

xml方式的話和以前Spring整合mybatis沒有太大的區(qū)別,在這里可以使用Mybatis-Generator自動(dòng)生成代碼少些一點(diǎn)代碼板丽,其余的話就不多介紹了

整合通用Mapper

不管是使用注解方式還是XML方式都還是會(huì)存在一個(gè)什么都得自己動(dòng)手的情況衣式,接下來的話,我們整合一個(gè)通用的Mapper檐什,在mybatis中體驗(yàn)jpa的感覺
引用依賴

<!-- 引入通用mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>

繼承BaseMapper

package com.priv.gabriel.demoformybatis.mapper;


import com.priv.gabriel.demoformybatis.entity.User;
import org.apache.ibatis.annotations.Mapper;
import tk.mybatis.mapper.common.BaseMapper;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-14
 * @Description:
 */
@Mapper
public interface UserCommonMapper extends BaseMapper<User> {
}

接著在Controller中調(diào)用

   @Autowired
    private UserCommonMapper mapper;

    @RequestMapping("/testCommonMapperForSelectAll")
    public List<User> testCommonMapper(){
        return mapper.selectAll();
    }

關(guān)于mybatis的擴(kuò)展很多碴卧,還有像mybatis-plus,關(guān)于這個(gè)話有時(shí)間再說吧乃正,ε=ε=ε=┏(゜ロ゜;)┛

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末住册,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子瓮具,更是在濱河造成了極大的恐慌荧飞,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,084評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件名党,死亡現(xiàn)場離奇詭異叹阔,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)传睹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評論 3 392
  • 文/潘曉璐 我一進(jìn)店門耳幢,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人欧啤,你說我怎么就攤上這事睛藻。” “怎么了邢隧?”我有些...
    開封第一講書人閱讀 163,450評論 0 353
  • 文/不壞的土叔 我叫張陵店印,是天一觀的道長。 經(jīng)常有香客問我倒慧,道長按摘,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,322評論 1 293
  • 正文 為了忘掉前任纫谅,我火速辦了婚禮炫贤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘系宜。我一直安慰自己照激,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,370評論 6 390
  • 文/花漫 我一把揭開白布盹牧。 她就那樣靜靜地躺著俩垃,像睡著了一般励幼。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上口柳,一...
    開封第一講書人閱讀 51,274評論 1 300
  • 那天苹粟,我揣著相機(jī)與錄音,去河邊找鬼跃闹。 笑死嵌削,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的望艺。 我是一名探鬼主播苛秕,決...
    沈念sama閱讀 40,126評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼找默!你這毒婦竟也來了艇劫?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,980評論 0 275
  • 序言:老撾萬榮一對情侶失蹤惩激,失蹤者是張志新(化名)和其女友劉穎店煞,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體风钻,經(jīng)...
    沈念sama閱讀 45,414評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡顷蟀,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,599評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了骡技。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鸣个。...
    茶點(diǎn)故事閱讀 39,773評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖哮兰,靈堂內(nèi)的尸體忽然破棺而出毛萌,到底是詐尸還是另有隱情,我是刑警寧澤喝滞,帶...
    沈念sama閱讀 35,470評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站膏秫,受9級特大地震影響右遭,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜缤削,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,080評論 3 327
  • 文/蒙蒙 一窘哈、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧亭敢,春花似錦滚婉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽远剩。三九已至,卻和暖如春骇窍,著一層夾襖步出監(jiān)牢的瞬間瓜晤,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評論 1 269
  • 我被黑心中介騙來泰國打工腹纳, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留痢掠,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,865評論 2 370
  • 正文 我出身青樓嘲恍,卻偏偏與公主長得像足画,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子佃牛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,689評論 2 354

推薦閱讀更多精彩內(nèi)容