• 06、JavaWeb启程——MyBatis基础


    1、MyBatis基础

    1、MyBatis的概述

    【简介】: MyBatis是一款优秀的持久层框架,它支持定制SQL、存储过程以及高级映射。MyBatis避免了几乎所有JDBC代码和手动设置参数以及获取结果集。MyBatis可以使用简单的XML或注解来配置和映射原生类型、接口和Java的POJO为数据中的记录。

    【MyBatis框架架构图】:
    在这里插入图片描述
    【API接口层】:

    • 提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。
    • 接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。

    【数据处理层】:

    • 负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它的主要目的是根据调用的请求完成一次数据库操作。

    【基础支撑层】:

    • 负责最基础的功能支撑、包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。
    • 为上层的数据处理层提供最基础的支撑。

    2、环境准备

    1、添加项目需要的jar包

    • lombok-1.16.6.jar 用于自动生成getter和setter方法
    • mysql-connector-java-5.1.26-bin.jar MySql数据库的JDBC驱动包,访问MySQL必须导入的jar包
    • mybatis-3.4.5.jar mybatis核心jar包

    2、创建用户表

    CREATE TABLEuser`(
    `id` bigint(20) NOT NULL AUTO_INCREMENT,'name`varchar(255)DEFAULT NULL`age` int(255) DEFAULT NULL`salary` decima1 (10,0) DEFAULT NULLPRIMARY KEY ( `id`)
    )ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3、创建实体类

    package cn.simplelife.work.domain;
    
    import lombok.*;
    
    import java.math.BigDecimal;
    
    /**
     * @ClassName User
     * @Description
     * @Author simplelife
     * @Date 2022/10/14 15:08
     * @Version 1.0
     */
    @NoArgsConstructor
    @AllArgsConstructor
    @Getter
    @Setter
    @ToString
    public class User {
        private Long id;
        private String name;
        private Integer age;
        private BigDecimal salary;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    4、书写mybatis-config.xml配置文件

    • 在项目的resources下创建mybatis-config.xml配置文件
    • 拷贝xml约束
    • 书写配置信息
    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <properties resource="db.properties"/>
        <typeAliases>
            
            <package name="cn.simplelife.work.domain"/>
        typeAliases>
        
        <environments default="dev">
            
            <environment id="dev">
                
                <transactionManager type="JDBC"/>
                
                <dataSource type="POOLED">
                    
                    <property name="driver" value="${driverClassName}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                dataSource>
            environment>
        environments>
        <mappers>
            <mapper resource="cn/simplelife/work/mapper/UserMapper.xml"/>
        mappers>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    5、创建mapper映射文件

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="cn.simplelife.work.mapper.UserMapper">
        
        <insert id="insert" parameterType="cn.simplelife.work.domain.User" useGeneratedKeys="true" keyColumn="id"
                keyProperty="id">
            INSERT INTO user(name,age,salary) VALUES (#{name},#{age},#{salary})
        insert>
    
        <delete id="delete">
            DELETE FROM user WHERE  id=#{id}
        delete>
    
        <update id="update">
            UPDATE user SET name=#{name},age=#{age},salary=#{salary} WHERE id=#{id}
        update>
    
        <select id="selectOne" resultType="User">
            SELECT * FROM user WHERE id=#{id}
        select>
    
        <select id="selectAll" resultType="User">
            SELECT * FROM user
        select>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    6、DAO层开发

    package cn.simplelife.work.dao;
    
    import cn.simplelife.work.domain.User;
    
    import java.util.List;
    
    /**
     * @ClassName IUserDAO
     * @Description
     * @Author simplelife
     * @Date 2022/10/14 15:54
     * @Version 1.0
     */
    
    public interface IUserDAO {
        /**
         * 插入条用户信息
         *
         * @param user 要插入的用户信息
         */
        void insert(User user);
    
        /**
         * 根据id删除用户信息
         *
         * @param id 要删除的用户id
         */
        void delete(Long id);
    
        /**
         * 根据id来修改用户信息
         *
         * @param user 要修改的用户id+新的用户信息
         */
        void update(User user);
    
        /**
         * 根据id查询用户信息
         *
         * @param id 要查询的用户id
         * @return 返回查询的用户对象
         */
        User selectOne(Long id);
    
        /**
         * 查询所有的用户信息
         *
         * @return 返回用户信息列表
         */
        List<User> selectAll();
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    7、DAO层实现类开发

    package cn.simplelife.work.dao.impl;
    
    import cn.simplelife.work.dao.IUserDAO;
    import cn.simplelife.work.domain.User;
    import cn.simplelife.work.utils.MyBatisUtils;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @ClassName IUserDAOImpl
     * @Description
     * @Author simplelife
     * @Date 2022/10/14 15:59
     * @Version 1.0
     */
    
    public class IUserDAOImpl implements IUserDAO {
        @Override
        public void insert(User user) {
            SqlSession session = MyBatisUtils.getSqlSession();
            // 3、执行操作
            session.insert("cn.simplelife.work.mapper.UserMapper.insert", user);
            // 4、提交事务
            session.commit();
            // 5、释放资源
            session.close();
        }
    
        @Override
        public void delete(Long id) {
            try {
                // 1、加载配置文件,获取SqlSessionFactory对象
                SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
                // 2、获取sqlSession会话对象
                SqlSession sqlSession = factory.openSession();
                // 3、执行语句
                sqlSession.delete("cn.simplelife.work.mapper.UserMapper.delete", id);
                // 4、提交事务
                sqlSession.commit();
                // 5、释放资源
                sqlSession.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public void update(User user) {
            try {
                // 1、加载配置文件及获取factory对象
                SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
                // 2、获取sqlSession会话对象
                SqlSession sqlSession = factory.openSession();
                // 4、执行操作
                sqlSession.update("cn.simplelife.work.mapper.UserMapper.update", user);
                // 5、提交事务
                sqlSession.commit();
                // 6、释放资源
                sqlSession.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public User selectOne(Long id) {
            User user = null;
            try {
                // 1、加载配置文件
                SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
                // 2、获取sqlSession会话对象
                SqlSession sqlSession = factory.openSession();
                // 3、执行操作
                user = sqlSession.selectOne("cn.simplelife.work.mapper.UserMapper.selectOne", id);
                // 4、提交事务
                sqlSession.commit();
                // 5、释放资源
                sqlSession.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return user;
        }
    
        @Override
        public List<User> selectAll() {
            // 2、获取sqlSession对象
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            // 3、执行语句
            List<User> userList = sqlSession.selectList("cn.simplelife.work.mapper.UserMapper.selectAll");
            // 4、提交事务
            sqlSession.commit();
            // 5、释放资源
            sqlSession.close();
            return userList;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105

    8、抽取MyBatisUtils工具类

    package cn.simplelife.work.utils;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    
    /**
     * @ClassName MyBatisUtils
     * @Description
     * @Author simplelife
     * @Date 2022/10/14 20:05
     * @Version 1.0
     */
    
    public class MyBatisUtils {
        private MyBatisUtils() {
        }
    
        private static SqlSessionFactory factory = null;
    
        static {
            try {
                factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public static SqlSession getSqlSession() {
            return factory.openSession();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    3、MyBatis执行流程

    • 加载主配置文件到内存中,将数据封装成对象
    • 通过操作拿到访问数据库的基本信息,根据这些数据创建SqlSessionFactory对象
    • 从SqlSessionFactory对象中获取SqlSession对象然后执行SQL
    • 翻译sql
    • 使用预编译语句对象执行sql
  • 相关阅读:
    查找算法【哈希表】 - 处理冲突的方法:开放地址法-线性探测法
    InfiniBand网络带宽从SDR、DDR、QDR、FDR、EDR、HDR到NDR发展
    Vite快速创建Vue3项目
    【黑马-SpringCloud技术栈】【04】Nacos注册中心
    监控电脑的软件叫什么丨科普小知识
    python列出本地文件路径
    react入门基础
    浙政钉用户登陆
    浅谈红黑树
    redis内存碎片整理
  • 原文地址:https://blog.csdn.net/m0_37911124/article/details/127532898