• 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

    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依赖包。

     
            <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中配置

    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配置,也可以在这里使用注解配置。我这里仅定义了几个简单的增删改查。

    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定义是为了解耦。

    <?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目录下)的作用是指定数据连接信息。

    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环境,接口映射和接口配置。

    <?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查询数据

    以下是调用示例:

    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);
        }
    }
    
  • 相关阅读:
    计算机毕业设计选题Java毕业设计之基于SSM实现的仓库管理系统
    OpenWrt之feeds.conf.default详解
    19 css 选择器用类名、节点名、id来获取节点内容
    云计算和大数据处理
    Java八大排序算法
    对Excel表中归类的文件夹进行自动分类
    一览JavaScript模块化 包含Commonjs、AMD、CMD、ES6 modules总结
    关于2023中国(济南)国际换热传热技术与应用展览会通知
    校园报修维修小程序,微信小程序报修系统,微信小程序宿舍报修系统毕设作品
    Vue研习录(03)——条件渲染讲解及示例分析
  • 原文地址:https://blog.csdn.net/gghhb12/article/details/139611982