75、SpringBoot 整合 MyBatis------使用 Mapper 作为 Dao 组件

SpringBoot 整合 MyBatis------使用 Mapper 作为 Dao 组件

总结:
添加一个User类和Mapper接口,
在Mapper接口这个类上面添加@Mapper注解,就可以和数据库进行映射了,
然后在mapper接口写方法和sql,
在测试类进行测试。
pom文件就添加个mybatis-spring-boot-starter 的组件,用于SpringBoot整合Mybatis的需要
就ok了

其实是MyBatis去整合SpringBoot ,SpringBoot本身没有去整合MyBatis(看不上MyBatis)。
如:mybatis-spring-boot-starter ,这个整合的组件是以MyBaits开头的,表示这个整合进SpringBoot的功能组件是MyBatis搞出来的。


MyBatis框架

MyBatis只是一个SQL映射框架,并不是ORM框架。它只是负责将ResultSet映射成对象List。

它不像Jpa(Hibernate)那么强大、但它比JPA(Hibernate)用起来更简单、更容易上手。

核心组件:用Mapper充当DAO组件,而且这些mapper只需提供接口,MyBatis会负责为它们生成实现类。


MyBatis整合Spring Boot

MyBatis不整合Spring Boot(或Spring)时,MyBatis需要自行使用SqlSession的getMapper()方法来获取Mapper组件;

整合Spring Boot(或Spring)时,Spring容器会负责生成Mapper组件,

并能将Mapper组件注入到其他组件(如Service组件)中。


MyBatis整合Spring Boot 与 整合Spring的区别

区别只是整合Spring则需要开发者自行配置DataSource、SqlSessionFactory等基础资源

整合Spring Boot不再需要开发者自行配置DataSource和SqlSessionFactory——因为Spring Boot的功能就是自动配置。

【补充:】如果你要用MyBatis访问多数据库,必须手动配置多个数据源、多个SqlSessionFactory——自动配置就失效的。


创建Mapper组件的两种方式:


Spring Boot或Spring如何识别哪些是Mapper组件呢?有两种方式:

方式1:为每个Mapper接口添加@Mapper注解即可

方式2:在应用配置类(比如程序主类、或带@Configuration注解修饰的类)上添加@MapperScan注解,该注解需要指定一个包名,用于告诉Spring Boot或Spring到哪个包下搜索Mapper组件。

MyBatis官方文档推荐使用第一种方式,可能这种方式更加安全、可靠。
——因为:Spring Boot与MyBatis的整合,其实是由Mybatis来提供的,并不是由Spring boot提供的。


基于Mapper的开发方式

1、定义映射的对象类,非常普通的POJO,甚至无需任何注解。

2、定义Mapper接口(只需要接口), Mapper接口中的每个方法都需要提供SQL语句。
不同的SQL语句使用对应的注解来提供


代码演示

演示使用 springboot整个mapper组件来关联数据库

实体类 User

在这里插入图片描述

Mapper

Mapper 组件,就是Dao 接口,贴上了这个 @Mapper 注解,就可以和数据库进行映射了。
在这里写sql
在这里插入图片描述
在这里插入图片描述

UserMapperTest 测试类

对mapper的方法进行测试
都是成功的
在这里插入图片描述
在这里插入图片描述

application.properties 配置文件

连接数据库,输出sql语句

如果想看到SQL语句输出,需要将Mapper组件的日志级别设置为debug
在这里插入图片描述

如果注释掉,就看不到了,如图
在这里插入图片描述

pom.xml

MyBatis 整合在 SpringBoot 需要添加的组件
在这里插入图片描述

完整代码:

User

package cn.ljh.app.domain;

import lombok.Data;

//普通的java类
@Data
public class User
{
    private Integer id;
    private String name;
    private String password;
    private int age;

    public User()
    {
    }

    public User(Integer id, String name, String password, int age)
    {
        this.id = id;
        this.name = name;
        this.password = password;
        this.age = age;
    }

    @Override
    public String toString()
    {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

UserMapper

package cn.ljh.app.dao;


import cn.ljh.app.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper
{
    //Mapper接口中的每个方法都需要为它提供SQL语句

    //增
    @Insert("insert into user_inf values (null,#{name},#{password},#{age})")
    int save(User user);

    //删
    @Delete("delete from user_inf where user_id = #{id}")
    int deleteById(Integer id);

    //改
    @Update("update user_inf set name = #{name} , password = #{password} ,age = #{age} where user_id = #{id}")
    int update(User user);

    //查
    @Select("select user_id as id , name , password , age from user_inf where user_id = #{id}")
    User findById(Integer id);


    //根据名字模糊查询
    @Select("select user_id as id , name , password , age from user_inf where name like #{namePattern}")
    List<User> findByNameLike(String namePattern);

    //根据年龄大小进行范围查询
    @Select("select user_id as id ,name , password , age from user_inf where age > #{startAge}")
    List<User> findByAgeGreaterThan(int startAge);


    //根据年龄区间进行范围查询
    @Select("select user_id as id ,name , password , age from user_inf where age between #{startAge} and #{endAge} ")
    List<User> findByAgeBetween(@Param("startAge") int startAge, @Param("endAge") int endAge);

    //根据密码模糊查询
    @Select("select user_id as id ,name , password , age from user_inf where password like #{passwordPattern}")
    List<User> findBySql(String passwordPattern);

    //根据年龄范围修改名字
    @Update("update user_inf set name = #{name} where age between #{startAge} and #{startAge}")
    int updateNameByAge(@Param("name") String name, @Param("startAge") int startAge, @Param("endAge") int endAge);

}

UserMapperTest

package cn.ljh.app;

import cn.ljh.app.dao.UserMapper;
import cn.ljh.app.domain.User;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class UserMapperTest
{
    @Autowired
    private UserMapper userMapper;

    //添加user对象
    @ParameterizedTest
    @CsvSource({"aa,xxx,2", "bb,xxx,3"})
    public void testSave(String name, String password, int age)
    {
        //没有id,save就是添加
        int save = userMapper.save(new User(null, name, password, age));
        System.err.println(save);
    }

    //根据id删除用户对象
    @ParameterizedTest
    @ValueSource(ints = {15})
    public void testDelete(Integer id)
    {
        userMapper.deleteById(id);
    }

    //根据id修改对象
    @ParameterizedTest
    @CsvSource({"13,a,x,2"})
    public void testUpdate(Integer id, String name, String password, int age)
    {
        //有id,save就是修改
        int update = userMapper.update(new User(id, name, password, age));
        System.err.println(update);
    }



    //根据id查询对象
    @ParameterizedTest
    @ValueSource(ints = {1})
    public void testFindById(Integer id)
    {
        User user = userMapper.findById(id);
        System.err.println(user);
    }

    //根据名字模糊查询
    @ParameterizedTest
    @ValueSource(strings = {"孙%", "%精"})
    public void testFindByNameLike(String namePattern)
    {
        List<User> users = userMapper.findByNameLike(namePattern);
        users.forEach(System.err::println);
    }

    //根据年龄大小进行范围查询
    @ParameterizedTest
    @ValueSource(ints = {500, 10})
    public void testFindByAgeGreaterThan(int startAge)
    {
        List<User> users = userMapper.findByAgeGreaterThan(startAge);
        users.forEach(System.err::println);
    }





    //根据年龄区间进行范围查询
    @ParameterizedTest
    @CsvSource({"15,20", "500,1000"})
    public void testFindByAgeBetween(int startAge, int endAge)
    {
        List<User> users = userMapper.findByAgeBetween(startAge, endAge);
        users.forEach(System.err::println);
    }


    //根据密码模糊查询
    @ParameterizedTest
    @ValueSource(strings = {"niu%", "%3"})
    public void testFindBySql(String passwordPattern)
    {
        List<User> users = userMapper.findBySql(passwordPattern);
        users.forEach(System.err::println);
    }

    //根据年龄范围修改名字
    @ParameterizedTest
    @CsvSource({"牛魔王dd,800,1000"})
    @Transactional
    @Rollback(false)
    public void testUpdateNameByAge(String name, int startAge, int endAge)
    {
        int i = userMapper.updateNameByAge(name, startAge, endAge);
    }
}

application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
# 如果想看到SQL语句输出,需要将Mapper组件的日志级别设置为debug
logging.level.cn.ljh.app.dao=debug

db.sql

-- drop database springboot;
-- create database springboot;
-- use springboot;

-- 创建user_inf表
create table user_inf
(
    user_id int primary key auto_increment,
    name varchar(255),
    password varchar(255),
    age int
);
-- 向user_inf表插入数据
insert into user_inf
values
(null, '孙悟空', 'sun123', 500),
(null, '牛魔王', 'niu123', 800),
(null, '猪八戒', 'zhu123', 600),
(null, '沙和尚', 'sha123', 580),
(null, '白鼠精', 'bai123', 23),
(null, '蜘蛛精', 'zhi123', 18),
(null, '玉面狐狸', 'yumian123', 21),
(null, '杏仙', 'xing123', 19);

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
    </parent>
    <groupId>cn.ljh</groupId>
    <artifactId>MyBatis_Mapper</artifactId>
    <version>1.0.0</version>
    <name>MyBatis_Mapper</name>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <!-- 导入 MyBatis 整合 spring boot 的 starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 整合 MyBatis-Plus 的步骤如下: 1.添加 MyBatis-Plus 和 MyBatis-Spring-Boot-Starter 依赖。在 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.2</version> </dependency> ``` 2.添加数据库配置。在 application.yml 文件中添加以下配置: ``` spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false username: root password: root ``` 3.创建 Mapper 接口。在 mapper 接口上添加 @Mapper 注解,并且继承 BaseMapper 接口,例如: ``` @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 4.创建 Mapper XML 文件。在 resources 目录下创建 mapper 目录,并在该目录下创建与 Mapper 接口同名的 XML 文件,例如: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.example.demo.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.example.demo.entity.User"> <id column="id" property="id" /> <result column="name" property="name" /> <result column="age" property="age" /> <result column="email" property="email" /> </resultMap> <select id="selectById" resultMap="BaseResultMap"> select * from user where id=#{id} </select> </mapper> ``` 5.在 Service 中调用 Mapper 接口。例如: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.selectById(id); } } ``` 这样,Spring Boot 就成功整合MyBatis-Plus 和 Mapper XML 文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_L_J_H_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值