溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot框架如何整合Mybatis

發(fā)布時間:2022-03-04 15:13:22 來源:億速云 閱讀:137 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“SpringBoot框架如何整合Mybatis”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“SpringBoot框架如何整合Mybatis”這篇文章吧。

步驟 1 添加mybatis-starter依賴

訪問:https://mvnrepository.com/

搜索mybatis,找到 MyBatis Spring Boot Starter ,點進去,復(fù)制到pom.xml

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

我們就用最新的即可。

步驟 2 如何配置mybatis到SpringBoot項目

mybatis:
  mapper-locations: classpath:mybatis/*.xml
  type-aliases-package: com.java18.vipmgr.pojo

mapper-locations是定義xml文件所在的目錄。

SpringBoot框架如何整合Mybatis

我們放在resources下面,也就是classpath中。

UserMapper.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.java18.vipmgr.mapper.UserMapper">
    <select id="getAllUsers" resultType="User">
        select * from users
    </select>
</mapper>

里面就寫了一個方法,注意 namespace=“com.java18.vipmgr.mapper.UserMapper” 這個配置。這個表示該xml文件是和UserMapper.java綁定的。

SpringBoot框架如何整合Mybatis

代碼如下

@Mapper
public interface UserMapper {
    public List<User> getAllUsers();
}

接下來再看 resultType=“User” 這個配置,為什么返回類型知道是User對象呢?

User類在這:

SpringBoot框架如何整合Mybatis

@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer points;
}

那是因為,我們在application.yml中做了綁定,也就是這個:

mybatis:
  mapper-locations: classpath:mybatis/*.xml
  <font color="#c24f4a">type-aliases-package: com.java18.vipmgr.pojo</font>

所以,當(dāng)我們寫 resultType=“User” 的時候,就會自動匹配到com.java18.vipmgr.pojo包下面的User類。

至此,配置mybatis到SpringBoot項目就成功了!

步驟 3 測試查詢

SpringBoot框架如何整合Mybatis

還是在controller中做測試,首先引入Mapper

@Autowired
UserMapper userMapper;

然后編寫查詢方法

@GetMapping("getAllViaMybatis")
public  List<User> getAllViaMybatis(){
    return userMapper.getAllUsers();
}

啟動服務(wù),訪問http://localhost:8888/user/getAllViaMybatis,得

[{“id”:1,“username”:“zhangsan”,“password”:“123”,“points”:1000},{“id”:2,“username”:“l(fā)isi”,“password”:“123”,“points”:200}]

步驟 4 mybatis注解方式

除了xml的方式,我們還可以使用mybatis注解方式
UserMapper.java

@Mapper
public interface UserMapper {
    public List<User> getAllUsers();

    @Select("select * from users where id = #{param1}")
    User findById(String id);

}

增加了一個方法,打了@Select注解,接收ID為參數(shù),這邊用的是mybatis的順序傳參法。

對應(yīng)的Controller方法

@GetMapping("findById")
public  User findById(String id){
    return userMapper.findById(id);
}

測試url:http://localhost:8888/user/findById?id=2

返回 {“id”:2,“username”:“l(fā)isi”,“password”:“123”,“points”:200}

這種的好處就是不用寫xml了,很方便,缺點是不夠靈活。

步驟 5 用注解方式做一個新增操作

mapper代碼

@Update("insert into users values (null,#{username},#{password},#{points})")
void addUser(User user);

controller代碼

@GetMapping("addUser")
public  boolean addUser(){
    User user = new User();
    user.setUsername("wangwu");
    user.setPassword("123");
    user.setPoints(1000);
    userMapper.addUser(user);
    return true;
}

測試效果

SpringBoot框架如何整合Mybatis

PS: 因為id是自動增長的,所以插入null即可。

步驟 6 整合PageHelper分頁插件

pom.xml

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>

導(dǎo)入這個依賴就行了,你可以什么都不配置的。

UserController,原來的查詢方法改成這樣

@GetMapping("getAllViaMybatis")
public  PageInfo getAllViaMybatis(int page,int rows){
    PageHelper.startPage(page,rows);
    PageInfo pageInfo = new PageInfo(userMapper.getAllUsers());
    return pageInfo;
}

接收page和rows作為分頁參數(shù)

測試url http://localhost:8888/user/getAllViaMybatis?page=1&rows=10

測試前記得多弄幾條數(shù)據(jù)在數(shù)據(jù)庫。

步驟 7 拓展知識:mybatis四種傳參方式

通過對象傳參

<insert id="insertEmp" parameterType="org.zhang.pojo.Emp">
    insert into emp (ename,job,hiredate,sal) values (#{ename},#{job},#{hiredate},#{sal});
    <selectKey resultType="int" keyColumn="empno" keyProperty="empno" order="AFTER">
        select last_insert_id()
    </selectKey>
</insert>

方式1:順序傳參法

<!--    此時因為有多個參數(shù)  所以參數(shù)類型不能逐一制定 可以省略  有mybatis自動匹配-->
    <update id="updateEmpByNo2">
            update emp set ename=#{param1} where empno=#{param2}
    </update>

方式2:@Param注解傳參法
就是在方法的參數(shù)列表中置頂要傳的參數(shù),然后在sql中直接寫

public void updateEmpByNo2(@Param("name") String ename,@Param("no") Integer empno) throws IOException;
<update id="updateEmpByNo2">
        update emp set ename=#{name} where empno=#{no}
</update>

方式3:Map傳參法

重點就是 parameterType="hashmap" 這句話

public void updateEmpByNo3(Map<String,Object> argMap) throws IOException;
<update id="updateEmpByNo3" parameterType="hashmap">
        update emp set ename=#{name} where empno=#{no}
</update>

方式4:Java Bean傳參法

public User selectUser(Emp emp);
  
 <select id="selectUser" parameterType="org.zhang.pojo.Emp" resultMap="Emp">
     select * from user
     where user_name = #{userName} and dept_id = #{deptId}
 </select>

步驟 8 Mybatis中#{}和${}的區(qū)別是什么?

KaTeX parse error: Expected 'EOF', got '#' at position 10: {}是字符串替換,#?{}是預(yù)處理; Mybatis…{}時,就是把${}直接替換成變量的值。

而Mybatis在處理#{}時,會對sql語句進行預(yù)處理,將sql中的#{}替換為?號,調(diào)用PreparedStatement的set方法來賦值;

使用#{}可以有效的防止SQL注入,提高系統(tǒng)安全性。

步驟 9 Mybatis中模糊查詢like語句該怎么寫?

第1種:在Java代碼中添加sql通配符,就是把通配符也寫在字符串里面帶進去。(推薦).

string wildcardname = “%smi%”;
list<name> names = mapper.selectlike(wildcardname);

對應(yīng)的xml:

select * from foo where bar like #{value}

第2種:在sql語句中拼接通配符,會引起sql注入(不推薦)

string wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);

 <span >對應(yīng)的xml:</span>
    <select id=”selectlike”>
         select * from foo where bar like "%"${value}"%"
    </select>

步驟 10 SpringBoot整合Mybatis-plus

MyBatis-Plus (opens new window)(簡稱 MP)是一個 MyBatis (opens new window)的增強工具,在 MyBatis 的基礎(chǔ)上只做增強不做改變,為簡化開發(fā)、提高效率而生。

SpringBoot框架如何整合Mybatis

官網(wǎng)文檔地址:https://mp.baomidou.com/guide/

首先添加依賴,這一步是必不可少的。

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1.tmp</version>
</dependency>

步驟 11 Mybatis-plus 如何與 Mybatis 共存?

因為上面的代碼都是基于Mybatis的,所以,我們需要讓他們共存。辦法就是修改application.yml

mybatis-plus:
  mapper-locations: classpath:mybatis/*.xml
  type-aliases-package: com.java18.vipmgr.pojo

把mybayis改成mybatis-plus就可以了,之前的功能一個都不影響!

步驟 12 快速上手Mybatis-plus

因為我們的類名和表明不一致,所以需要做一個配置

User.java

@Data
@TableName("users")
public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer points;
}

UserMapper.java

public interface UserMapper extends BaseMapper<User> {
 //省略之前的代碼
}

繼承了BaseMapper就可以擁有很多CRUD方法,這一點和JPA很像。

UserController.java

@GetMapping("getAllViaMybatisPlus")
public  IPage<User> getAllViaMybatisPlus(Integer page,Integer rows){
    IPage<User> pageInfo = new Page<>(page, rows);//參數(shù)一是當(dāng)前頁,參數(shù)二是每頁個數(shù)
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    pageInfo = userMapper.selectPage(pageInfo,wrapper);
    return pageInfo;
}

測試URL:http://localhost:8888/user/getAllViaMybatisPlus?page=1&rows=10

{“records”:[{“id”:1,“username”:“zhangsan”,“password”:“123”,“points”:1000},{“id”:2,“username”:“l(fā)isi”,“password”:“123”,“points”:200},{“id”:3,“username”:“wangwu”,“password”:“123”,“points”:1000},{“id”:4,“username”:“蔡互聽”,“password”:“123”,“points”:1000},{“id”:5,“username”:“荀傍支”,“password”:“123”,“points”:1000},{“id”:6,“username”:“養(yǎng)繡洋”,“password”:“123”,“points”:1000},{“id”:7,“username”:“夔惑腔”,“password”:“123”,“points”:1000},{“id”:8,“username”:“戎悅下”,“password”:“123”,“points”:1000},{“id”:9,“username”:“厲觸企”,“password”:“123”,“points”:1000},{“id”:10,“username”:“陸糟調(diào)”,“password”:“123”,“points”:1000}],“total”:22,“size”:10,“current”:1,“orders”:[],“hitCount”:false,“searchCount”:true,“pages”:3}

以上是“SpringBoot框架如何整合Mybatis”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI