当前位置:首页 > 编程笔记 > 正文
已解决

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

来自网友在路上 121821提问 提问时间:2023-09-24 18:16:54阅读次数: 21

最佳答案 问答题库218位专家为你答疑解惑

总结:
添加一个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组件来关联数据库

一个普通的java类
在这里插入图片描述

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;}@Overridepublic 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
{@Autowiredprivate 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>
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"75、SpringBoot 整合 MyBatis------使用 Mapper 作为 Dao 组件":http://eshow365.cn/6-12928-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!