5、SpringBoot集成MyBatis框架


前言

MyBatis 是一个持久层与数据库进行交互的框架。它支持自定义 SQL、存储过程以及高级映射。

一、使用步骤

1.通过Idea工具构建项目

  1. 在界面可以选择对应的依赖会自动导入。本示例使用的JDK1.8和Maven。
    在这里插入图片描述
    Mybatis也可以手动导入依赖:
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
  1. 在yml文件添加数据源配置。
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://192.168.0.101/test01?useUnicode=yes&characterEncoding=UTF8
  1. 创建一个对象实体类。
package com.example.entity;
public class TestObj {
    private Integer id;
    private String name;
    private String sex;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "TestObj{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

  1. 创建Mapper接口类。
package com.example.mapper;
import com.example.entity.TestObj;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface EmpMapper {

    List<TestObj> select();

    TestObj selectEmpById(Integer id);

    Integer add(TestObj testObj);

    Integer update(TestObj testObj);

    Integer delete(Integer id);
}

  1. 在resources下创建mapper目录并创建TextObj.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.example.mapper.TestObjMapper">

    <select id="selectObj" resultType="TestObj">
        select * from test20
    </select>

    <select id="selectById" resultType="TestObj">
        select * from test20 where id = #{id}
    </select>

    <insert id="add" parameterType="TestObj">
        insert into test20 (name,sex) values (#{name},#{sex})
    </insert>

    <update id="update" parameterType="TestObj">
        update test20 set name=#{name} where id = #{id}
    </update>

    <delete id="delete" parameterType="int">
        delete from test20 where id = #{id}
    </delete>
</mapper>

  1. 在yml文件添加MyBatis配置。
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.entity
  1. 创建Controller类。
package com.example.controller;
import com.example.entity.TestObj;
import com.example.mapper.TestObjMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TestController {
    @Autowired
    private TestObjMapper testObjMapper;
    @GetMapping("/list")
    public List<TestObj> test20List() {
        List<TestObj> maps = testObjMapper.selectObj();
        return maps;
    }

    @GetMapping("/add")
    public String addInfo() {
        testObjMapper.add(new TestObj("wangwu", "2"));
        return "success";
    }

    @GetMapping("/update/{id}")
    public String update(@PathVariable("id") Integer id) {
        String name = "list";
        testObjMapper.update(new TestObj(id, "dbing", "5"));
        return "update success";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        testObjMapper.delete(id);
        return "delete success";
    }
}
  1. 错误信息。
    启动报错:
    Invalid bound statement (not found): com.example.mapper.TestObjMapper.add] with root cause
    要注意这里的 mapper-locations不要搞成了这个config-locations 否则就会报上面错误。
    mybatis:
    type-aliases-package: com.example.entity
    mapper-locations: classpath:mapper/*.xml

  2. 测试结果打印
    修改访问:http://localhost:8889/update/3
    查询访问:http://localhost:8889/list 打印 [{“id”:3,“name”:“dbing”,“sex”:“2”}]

总结

MyBatis框架有优点灵活性比较高、降低了与代码之间的耦合度、配置比较规范。缺点是配置错了有时候排查起来比较费劲、编写sql比较繁琐。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
springboot集成mybatis框架的步骤如下: 1. 首先,在项目的pom.xml文件中添加mybatis的依赖。你可以使用以下的依赖配置来添加mybatis-spring-boot-starter依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency> ``` 2. 然后,在springboot的启动类上添加@MapperScan注解,指定mapper接口的包名,让springboot能够扫描到这些接口: ```java @MapperScan(basePackages = "mapper类所放的包名") @SpringBootApplication public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 3. 接下来,需要进行mybatis的配置。在application.properties或application.yml文件中添加mybatis的相关配置: ```yaml # mybatis配置 mybatis: check-config-location: true # 检查mybatis的配置文件位置 config-location: "classpath:mybatis/mybatis-config.xml" # mybatis的配置文件路径 mapper-locations: "classpath:mybatis/mapper/*Mapper.xml" # mapper接口的xml文件路径 type-aliases-package: "com.example.awesomespring.dao.entity.*" # mapper接口对应的实体类路径 ``` 通过以上步骤,你就成功地集成mybatis框架springboot项目中。这样,你就可以使用mybatis来进行数据库的持久化操作了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [手把手教你springboot集成mybatis](https://blog.csdn.net/Trouvailless/article/details/126315399)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追风★少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值