Spring 中使用MyBatis

一、Mybatis 的作用

1、MyBatis(前身为iBatis)是一个开源的Java持久层框架,它主要用于与数据库交互,帮助开发者更轻松地进行数据库操作。

持久层:指的是就是数据访问层(dao),是用来操作数据库的。

2、MyBatis 提供了一种简单而强大的方式来执行数据库操作,包括查询、插入、更新和删除。支持几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。开发者可以使用XML配置文件或者注解来定义SQL语句,并且可以将SQL语句的参数映射到Java对象,以便进行数据库操作。

ORM是什么 ?

ORM(Object Relation Mapping)对象关系映射,是一种思想,主要包含三种对应关系:

关系映射 对应关系
类和表对应 一个pojo类 ←→ 一张数据库表
字段和列名对应 pojo类中的一个字段 ←→ 数据库表中的一列
类实例化对象和数据对应 pojo类的一个对象 ←→ 数据库表中的一行数据

ORM思想是所有持久层框架的基本思想,也是目前所有数据传输的思想。就是把数据和对象一一对应起来。从本质上来说SpringMVC也是做的这样的事情,数据在页面时,传到后台就成了对象。

3、MyBatis 提供了缓存机制,可以帮助提高查询性能。你可以配置缓存来存储查询结果,以便在后续查询中重用结果,从而减少数据库访问次数。

4、MyBatis 支持事务管理,可以确保数据库操作的原子性和一致性。你可以通过配置或编程方式管理事务,以满足应用程序的需求。

二、Spring中MyBatis的使用步骤

2.1 创建数据库和表

请自行安装数据库并创建表,例如我的数据库名为yiqifu

sql 复制代码
CREATE TABLE `U_USER` (
`id`  int(255) NULL ,
`nickname`  varchar(255) NULL 
);

2.2 添加maven依赖

分别添加mysql-connector-java(用于连接mysql数据库)、mybatis(mybatis核心库)、mybatis-spring(在spring中使用mybatis的库)的maven依赖包。

java 复制代码
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.29</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
        
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.11</version>
        </dependency>
        <!--mybatis-spring包是适配包,帮助你在Spring中使用MyBatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
 
        <!--可以使用阿里巴巴的DruidDataSource-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.29</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
            <scope>test</scope>
        </dependency>

3.3 编写实体类

根据数据表的字段创建一个实体类,各字段可以不跟数据库一致。对应关系可以在Mapper.xml中配置

java 复制代码
package top.yiqifu.study.p061_mybatis;
 
public class UserEntity {
 
    public int id;
    public String name;
 
 
    public UserEntity(){
 
    }
    public UserEntity(int id, String name) {
        this.id = id;
        this.name = name;
    }
 
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public String toString() {
        return "UserEntity{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

2.4 创建UserMapper接口

UserMapper接口的作用是告诉mybatis您要对数据库执行那些操作。具体实现类由Spring AOP完成。其中执行的SQL语句可以通过Mappser.xml配置,也可以在这里使用注解配置。我这里仅定义了几个简单的增删改查。

java 复制代码
package top.yiqifu.study.p061_mybatis;
 
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
 
import java.util.List;
 
@Mapper
public interface UserMapper {
 
    void insert(UserEntity user);
 
    void deleteById(Integer id);
 
    void update(UserEntity user);
 
    List<UserEntity> findAll();
 
    @Select("select * from u_user where id=#{id}")
    @Results({
        @Result(property = "name", column = "nickname"), // 指定属性名和列名的映射关系
    })
    UserEntity findById(Integer id);
}

2.5 配置UserMapper.xml

UserMapper.xml的作用是告诉mybatis您在UserMapper接口定义的方法具体使用什么样的SQL及其他约束。我这里简单配置了UserMapper接口中每个方法。

注:其实也可以直接在UserMapper接口中使用注解定义(请看findById方法),使用XML定义是为了解耦。

java 复制代码
<?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">
 
 
<!-- namespace 对应到 接口上 就不需要实例化了 -->
<mapper namespace="top.yiqifu.study.p061_mybatis.UserMapper">
 
    <resultMap type="top.yiqifu.study.p061_mybatis.UserEntity" id="BaseResultMap">
        <!-- column 表里的字段 -->
        <!-- property 实体对象里的属性 -->
        <result column="id" property="id"/>
        <result column="nickname" property="name"/>
    </resultMap>
 
    <insert id="insert" parameterType="top.yiqifu.study.p061_mybatis.UserEntity">
    insert into u_user(nickname) values(#{name})
    </insert>
 
    <insert id="deleteById" parameterType="Integer">
    delete  from u_user where id=#{id}
    </insert>
 
    <insert id="update" parameterType="top.yiqifu.study.p061_mybatis.UserEntity">
    update u_user set nickname=#{name} where id=#{id}
    </insert>
 
    <select id="findAll" resultMap="BaseResultMap">
      select * from u_user
    </select>
 
 
</mapper>

2.6 配置数据库连接信息 JDBC

配置jdbc.properties(放在resources目录下)的作用是指定数据连接信息。

java 复制代码
database.driver=com.mysql.cj.jdbc.Driver
 
database.url=jdbc:mysql://localhost:3306/yiqifu?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
 
database.username=root
 
database.password=123456xxoo

2.7 在Spring中配置Mybatis

配置applicationContext-mybatis.xml(放在resources目录下)的作用将前的内容整合在起。包括mybatis的JDBC环境,接口映射和接口配置。

java 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd"
    >
 
    <context:component-scan base-package="top.yiqifu.study.p061_mybatis"></context:component-scan>
 
    <!-- 加载jdbc.properties配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
 
    <!-- 配置 MyBatis 数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.username}" />
        <property name="password" value="${database.password}" />
    </bean>
 
    <!-- 配置 mybatis Session -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--<property name="configLocation" value="classpath:mybatis-config.xml"></property>-->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>
 
    <!-- 扫描Mapper接口(Spring会使用AOP为其实现具体方法) -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="top.yiqifu.study.p061_mybatis" />
    </bean>
 
 
</beans>

2.8 在Spring中调用Mybatis查询数据

以下是调用示例:

java 复制代码
package top.yiqifu.study.p061_mybatis;
 
import org.springframework.context.support.ClassPathXmlApplicationContext;
import top.yiqifu.study.p051_proxy.Test011_StaticProxyDog;
import top.yiqifu.study.p051_proxy.Test041_Animal;
import top.yiqifu.study.p051_proxy.Test042_Dog;
 
 
public class Test001_Mybatis
{
    // 静态代理
    public static void main( String[] args )
    {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-mybatis.xml");
        UserMapper mapper = context.getBean("userMapper", UserMapper.class);
 
        for(String beanName : context.getBeanDefinitionNames()){
            System.out.println(beanName);
        }
 
 
        UserEntity user1 = new UserEntity();
        UserEntity user2 ;
        //添加
        user1.setName("test");
        mapper.insert(user1);
 
        int userId = 7;
        user2 = mapper.findById(userId);
        System.out.println(user2);
        //修改
        user1.setId(userId);
        user1.setName("new-test");
        mapper.update(user1);
 
        //查询
        user2 = mapper.findById(userId);
        System.out.println(user2);
 
        //删除
        //mapper.deleteById(userId);
 
 
        user2 = mapper.findById(userId);
        System.out.println(user2);
    }
}
相关推荐
To Be Clean Coder1 小时前
【Spring源码】getBean源码实战(二)
java·后端·spring
0和1的舞者3 小时前
SpringAOP详解(二)
学习·spring·切面·代理·知识·springaop
廋到被风吹走3 小时前
【Spring】Spring Cache 深度解析
java·后端·spring
七夜zippoe4 小时前
响应式编程基石 Project Reactor源码解读
java·spring·flux·响应式编程·mono·订阅机制
IT 行者4 小时前
Spring Framework 6.x 异常国际化完全指南:让错误信息“说“多国语言
java·后端·spring·异常处理·problemdetail·国际化i18n
鱼跃鹰飞5 小时前
面试题:Spring事务失效的八大场景
数据库·mysql·spring
子一!!5 小时前
MySQL数据库基础操作
数据库·mysql·oracle
DarkAthena5 小时前
【GaussDB】从 sqlplus 到 gsql:Shell 中执行 SQL 文件方案的迁移与改造
数据库·sql·oracle·gaussdb
wa的一声哭了5 小时前
内积空间 内积空间二
java·开发语言·python·spring·java-ee·django·maven
cike_y5 小时前
Spring使用注解开发
java·后端·spring·jdk1.8