概念

Mybatis就是对JDBC代码(将数据到保存到数据库的那一层代码)进行了封装。

JDBC的缺点

  1. 硬编码
    • 注册驱动、获取连接处的代码
    • SQL语句的代码
  2. 操作繁琐
    • 手动设置参数
    • 手动封装 ResultSet 结果集

Mybatis的优化

  1. 硬编码可以配置到配置文件
  2. 操作繁琐的地方mybatis都自动完成

Mybatis快速入门

  1. Mybatis的目录结构
    Mybatis目录
    需求:查询user表中所有的数据
    注:本项目基于Maven框架
  2. 数据库中创建user表,添加数据
create database mybatis;
use mybatis;

drop table if exists tb_user;

create table tb_user(
	id int primary key auto_increment,
	username varchar(20),
	password varchar(20),
	gender char(1),
	addr varchar(30)
);

INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京');
INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');
  1. 创建模块,导入坐标
    在pom.xml 配置文件(Maven项目的配置文件)中添加依赖的坐标
<dependencies>

    <!--mybatis 依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.5</version>
    </dependency>

    <!--mysql 驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>

    <!--junit 单元测试-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>

</dependencies>
  1. 编写 MyBatis 核心配置文件 – > 替换连接信息 解决硬编码问题。在模块下的 resources 目录下创建mybatis的配置文件 mybatis-config.xml,内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!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"/>
            <dataSource type="POOLED">
                <!-- 加载MySQL相关驱动 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--加载sql的映射文件-->
        <mapper resource="UserMapper.xml"/>
    </mappers>
    
</configuration>
  1. 编写 SQL 映射文件 --> 统一管理sql语句,解决硬编码问题。在模块的 resources 目录下创建映射配置文件 UserMapper.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">
<!--命令空间建议以表名命名-->
<mapper namespace="test">
<!--select标签标识这是一个查询语句,同理还有update,delete等语句-->
<!--命名空间+id标识唯一的sql语句-->
<!--resultType标识所操作的Java类在哪    -->
    <select id="selectAll" resultType="com.xzxhappy.pojo.User">
        select * from tb_user
    </select>
</mapper>
  1. 创建数据库对应类,在 com.xzxhappy.pojo 包下创建 User类
public class User {
    private int id;
    private String username;
    private String password;
    private String gender;
    private String addr;
    
    //省略了 setter 和 getter
}
  1. com.xzxhappy 包下编写 MybatisDemo 测试类
public class MyBatisDemo {

    public static void main(String[] args) throws IOException {
        //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 执行sql
        List<User> users = sqlSession.selectList("test.selectAll"); //参数是一个字符串,该字符串必须是映射配置文件的namespace.id
        System.out.println(users);
        //4. 释放资源
        sqlSession.close();
    }
}

MyBatis代理开发

优点:

  • 解决原生方式中的硬编码
  • 简化后期执行SQL

使用Mapper代理方式,必须满足以下要求:

  1. 定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下。
    mapper代理目录结构
    得出结论:其实resourses目录本质就是java目录

  2. 设置SQL映射文件的namespace属性为Mapper接口全限定名。(下图为mybatis-config.xml文件)
    mapper限定名
    注:如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载。如上图所示

  3. 在 Mapper 接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致。
    mapper方法名和返回值一致-1667391918113

核心配置文件mybatis-config.xml

  • 多环境配置
    在核心配置文件的 environments 标签中其实是可以配置多个 environment ,使用 id 给每段环境起名,在 environments 中使用 default='环境id' 来指定使用哪儿段配置。我们一般就配置一个 environment 即可。
<environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
        <environment id="test">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
  • 类型别名
    在映射配置文件(例如UserMapper.xml)中的 resultType 属性需要配置数据封装的类型(类的全限定名)。而每次这样写是特别麻烦的,Mybatis 提供了 类型别名(typeAliases) 可以简化这部分的书写。
    mybatis-config.xml文件中写入下面这个:
<typeAliases>
        <package name="com.xzxhappy.pojo"/>
</typeAliases>

那么UserMapper.xml中就可以这样来:

<!--下一行代码中的User也可以写小写,因为起别名后不区分大小写-->
<select id="selectAll" resultType="User">
<!--<select id="selectAll" resultType="com.xzxhappy.pojo.User">-->
        select * from tb_user
    </select>

Q.E.D.


在读程序猿+指弹发烧友+力量举、街头健身爱好者。