• 1 什么是MyBatis?


    1 MyBatis 概述

    MyBatis 是 apache 的一个开源项目 iBatis,2010年这个项目由 apache software founfation 迁移到 google code,并且改名为 MyBatis,2013年11月迁移到 Github。

    MyBatis 是一个实现数据持久化的开源框架(ORMapping:Object Relationship Mapping 对象关系映射),简单理解就是对 JDBC 进行封装

    2 MyBatis 的优点

    • 与JDBC相比,减少了50%以上的代码量。
    • MyBatis 是最简单的持久化框架,小巧并且简单易学。
    • MyBatis 相当灵活,不会对应用程序或者数据库的现有设计强加任何影响。SQL写在XML里,从程序代码中彻底分离,降低耦合度,便于统一管理和优化,并可重用。
    • 提供XML标签,支持编写动态SQL语句。
    • 提供映射标签,支持对象与数据库的ORM字段关系映射。

    3 MyBatis 的缺点

    • SQL语句的编写工作量较大,尤其是字段多、关联表多时,更是如此,对开发人员编写SQL语句的功底有一定要求。
    • SQL语句依赖于数据库,导致数据库移植性差,不能随意更换数据库。

    4 MyBatis 核心接口和类

    在这里插入图片描述

    5 MyBatis 的开发方式

    • 使用原生接口
    • Mapper代理实现自定义接口

    6 如何使用 Mybatis?

    • 新建 Maven 工程,pom.xml 添加依赖
    <dependencies>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.5version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.11version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>RELEASEversion>
            <scope>compilescope>
        dependency>
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 创建数据表
    USE mybatis;
    
    CREATE TABLE t_account(
    	id INT PRIMARY KEY AUTO_INCREMENT,
    	username VARCHAR(11),
    	PASSWORD VARCHAR(11),
    	age INT
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 新建数据表对应的实体类 Account
    package com.southwind.entity;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Account {
        private long id;
        private String username;
        private String password;
        private int age;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 创建 MyBatis 的配置文件 config.xml,文件名可自定义。
    
    DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        
        <environments default="development">
            
            
            <environment id="development">
                
                <transactionManager type="JDBC">transactionManager>
                
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"/>
                    <property name="username" value="root"/>
                    <property name="password" value="111111"/>
                dataSource>
            environment>
        environments>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    6.1 使用原生接口

    6.1.1 第一步

    MyBatis 框架需要开发者自定义SQL语句,写在Mapper.xml文件中。实际开发中,会为每个实体类创建对应的Mapper.xml,定义管理该对象数据的SQL。

    在这里插入图片描述

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.southwind.mapper.AccountMapper">
        <insert id="save" parameterType="com.southwind.entity.Account">
            insert into t_account(username,password,age) values(#{username},#{password},#{age})
        insert>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • namespace 通常设置为文件所在包+文件名的形式。
    • insert 标签:添加操作
    • select 标签:查询操作
    • update 标签:更新操作
    • delete 标签:删除操作
    • id 时实际调用 MyBatis 方法时需要用到的参数。
    • parameterType 是调用对应方法时参数的数据类型。

    6.1.2 第二步

    在全局配置文件 config.xml 中注册 AccountMapper.xml

    
    <mappers>
        <mapper resource="com/southwind/mapper/AccountMapper.xml">mapper>
    mappers>
    
    • 1
    • 2
    • 3
    • 4

    6.1.3 调用 MyBatis 的原生接口执行添加操作

    package com.southwind.test;
    
    import com.southwind.entity.Account;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.InputStream;
    
    public class Test {
        public static void main(String[] args) {
            // 加载MyBatis配置文件
            // 当前 inputStream 就是 inputstream 对应的一个数据流
            InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            SqlSession sqlsession = sqlSessionFactory.openSession();
            String statement = "com.southwind.mapper.AccountMapper.save";
            Account account = new Account(1L,"张三","123123",12);
            sqlsession.insert(statement,account);
            sqlsession.commit();
            sqlsession.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    开始运行,发现报错了:
    在这里插入图片描述

    • 原因:maven工程不能直接读取java里面的xml文件,只能读取resources里面的xml文件。
    • 解决方法:在pom.xml里边进行配置,使其能够读取java里边的xml文件。
    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                includes>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>*.xmlinclude>
                    <include>*.propertiesinclude>
                includes>
            resource>
        resources>
    build>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17


    若出现以下错误,请参考:https://www.cnblogs.com/smiler/p/9983146.html
    在这里插入图片描述

    6.2 通过 Mapper 代理实现自定义接口(推荐使用)

    • 自定义接口,定义相关业务方法
    • 编写与方法相对应的 Mapper.xml

    6.2.1 第一步

    • 自定义接口
    package com.southwind.repository;
    
    import com.southwind.entity.Account;
    
    import java.util.List;
    
    public interface AccountRepository {
        public int save(Account account);
        public int update(Account account);
        public int deleteById(long id);
        public List<Account> findAll();
        public Account findById(long id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    6.2.2 第二步

    创建接口对应的 Mapper.xml,定义接口方法对应的SQL语句。
    Statement 标签会根据 SQL 执行的业务选择 insert、delete、update、select。
    MyBatis 框架会根据规则字段创建接口实现类的代理对象。规则如下:

    • Mapper.xml 中 namespace 为接口的全类名
    • Mapper.xml 中 statement 的 id 为接口中对应的方法名
    • Mapper.xml 中 statement 的 parameterType 和接口中对应的方法的参数类型一致。
    • Mapper.xml 中 statement 的 resultType 和接口中对应方法的返回值类型一致。
      在这里插入图片描述
    <?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.southwind.repository.AccountRepository">
        <insert id="save" parameterType="com.southwind.entity.Account">
            insert into t_account(username,password,age) values(#{username},#{password},#{age})
        </insert>
        <update id="update" parameterType="com.southwind.entity.Account">
            update t_account set username = #{username},password=#{password},age=#{age}
        </update>
        <delete id="deleteById" parameterType="long">
            delete from t_account where id = #{id}
        </delete>
        <select id="findAll" resultType="com.southwind.entity.Account">
            select * from t_account
        </select>
        <select id="findById" parameterType="long" resultType="com.southwind.entity.Account">
            select * from t_account where id = #{id}
        </select>
    </mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    6.2.3 第三步

    在 config.xml 中注册 AccountRepository.xml

    <mapper resource="com/southwind/repository/AccountRepository.xml">mapper>
    
    • 1

    6.2.4 第四步

    调用接口的代理对象完成相关的业务操作

    package com.southwind.test;
    
    import com.southwind.entity.Account;
    import com.southwind.repository.AccountRepository;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.InputStream;
    import java.util.List;
    
    public class Test2 {
        public static void main(String[] args) {
            // 加载MyBatis配置文件
            // 当前 inputStream 就是 inputstream 对应的一个数据流
            InputStream inputStream = Test2.class.getClassLoader().getResourceAsStream("config.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            SqlSession sqlsession = sqlSessionFactory.openSession();
            // 获取实现接口的代理对象
            AccountRepository accountRepository = sqlsession.getMapper(AccountRepository.class);
            // 添加对象
            Account account = new Account(2L,"李四","123123",13);
            accountRepository.save(account);
            sqlsession.commit();
            List<Account> list = accountRepository.findAll();
            for(Account account1:list){
                System.out.println(account1);
            }
            sqlsession.close();
        }
    }
    
    • 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
  • 相关阅读:
    拥抱国产信创化,思迈特与云和恩墨完成产品兼容认证
    【NoSQL】Redis介绍、安装、性能优化
    【重识云原生】第六章容器6.1.1节——容器综述
    第十四章《多线程》第4节:控制线程
    sent2vec教程
    Django设计ORM模型步骤
    【实战详解】如何快速搭建接口自动化测试框架?Python + Requests
    抖音微短剧小程序平台:源码搭建与广告回传技术详解
    安徽某高校《数学建模》上机习题1选讲(建立范德蒙矩阵;解线性方程组)
    DCGAN-论文阅读笔记
  • 原文地址:https://blog.csdn.net/qq_52077925/article/details/126917667