MyBatis——简介

简介

1、引言

我们之前学习的关于数据库的工具包括:

JDBC --> Dbutils(QueryRunner) --> JdbcTemplate:工具

但 Spring 中的 JdbcTemplate 也只是一个工具,并不是一个框架(框架:整体解决方案)。

执行数据库操作的一般流程如下:

在这里插入图片描述

缺点为:功能简单;sql 语句编写在 java 代码里面;硬编码高耦合的方式

MyBatis:半自动,轻量级的框架

在这里插入图片描述

MyBatis 把 SQL 的编写交给配置文件,实现 Sql 与 java 编码分离;sql 是开发人员控制。


2、下载

https://github.com/mybatis/mybatis-3/

补充:IDEA 目录的分类

在这里插入图片描述

  • Sources Root(源码目录)

    一般用于标注类似 src 这种可编译目录只有 Sources 这种可编译目录才可以新建 Java 类和包

  • Test Sources Root(测试源码的目录)

    一般用于标注单元测试的资源文件目录。在 IDEA 中,如果测试代码不是放在此类型的文件夹中,无法使用 @Test 等测试注释。

  • Resources Root(源码所需资源的目录)

    一般用于标注资源文件目录。这里的资源可以是图片、配置文件等,我一般放配置文件,作用等同于放置在 Sources Root 根目录下。

  • Test Resources Root(测试资源的目录)

    一般用于标注单元测试的资源文件目录。资源目录下的文件是会被编译到输出目录下的。

  • Excluded(排除目录)

    一般用于标注排除目录。被排除的目录不会被 IntelliJ IDEA 创建索引,相当于被 IntelliJ IDEA 废弃,该目录下的代码文件是不具备代码检查和智能提示等常规代码功能


3、MyBatis-HelloWorld

https://mybatis.org/mybatis-3/zh/getting-started.html MyBatis 入门

3.1、数据库数据准备

CREATE TABLE tbl_employee(
	id INT(11) PRIMARY KEY auto_increment,
	last_name VARCHAR(255),
	gender CHAR(1),
	email VARCHAR(255)
);

3.2、封装类

创建一个 Employee 类,用来封装从数据库中查询的数据:

package mybatis.bean;

public class Employee {
    private Integer id;
    private String lastName;//此处应注意,lastname和数据库中的字段last_name不一致,故意设置的错误
    private String email;
    private String gender;

    public Employee() {
    }

    public Employee(Integer id, String lastName, String email, String gender) {
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getId() {
        return id;
    }

    public String getLastName() {
        return lastName;
    }

    public String getEmail() {
        return email;
    }

    public String getGender() {
        return gender;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender='" + gender + '\'' +
                '}';
    }
}

3.3、全局配置文件

mybatis-config.xml(全局配置文件)

内容:

  1. 配置数据库连接;
  2. 关联 sql 映射文件。

作用:

创建一个 SqlSessionFactory 对象。

<?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">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://10.150.104.5:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="Opfordream@0518"/>
            </dataSource>
            
        </environment>
    </environments>

    <!--将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中-->
    <mappers>
        <mapper resource="EmployeeMapper.xml"/>
    </mappers>
</configuration>

3.4、sql 映射文件

EmployeeMapper.xml(sql 映射文件)

内容:

配置每一个 sql,以及 sql 的封装规则等。

<?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="org.mybatis.example.BlogMapper">

    <!--namespace:命名空间
        id:唯一标识
        resultType:返回值类型
        #{id}:从传递过来的参数中取出id值-->

    <select id="selectEmp" resultType="mybatis.Employee">
        <!--在这里我们使用了别名,使得字段名和类的属性名相同-->
        select id,last_name lastName,email,gender from tbl_employee where id = #{id}
    </select>
</mapper>

3.5、编写一个测试类

public class MyBatisTest {
    /**
     * 1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象;
     * 2、sql映射文件:配置每一个sql,以及sql的封装规则等;
     * 3、将sql映射文件注册在全局配置文件中;
     * 4、写代码:
     *      1)  根据全局配置文件得到sqlSessionFactory;
     *      2)  使用sqlSessionFactory,获取到sqlSession对象使用它来执行增删改查
     *          一个sqlSession就是代表和数据库的一次会话,用完关闭
     *      3)  使用sql的唯一标志来告诉MyBatis执行哪个sql。sql都是保存在sql映射文件中的。
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2、获取sqlSession实例,能直接查询已经映射的sql语句
        try (SqlSession session = sqlSessionFactory.openSession()) {
            /*
            参数:
            sql的唯一标识:namespace+id
            执行sql要用的参数
         */
            Employee employee = session.selectOne("org.mybatis.example.BlogMapper.selectEmp", 1);

            System.out.println(employee);
            /*
            DEBUG 12-21 16:52:12,986 ==>  Preparing: select id,last_name lastName,email,gender 				from tbl_employee where id = ?  (BaseJdbcLogger.java:137) 
            DEBUG 12-21 16:52:13,057 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:137) 
            DEBUG 12-21 16:52:13,097 <==      Total: 1  (BaseJdbcLogger.java:137) 
            Employee{id=1, lastname='tom', email='tom@qq.com', gender='0'}
            */
        }

    }
}

整个项目框架结构:

在这里插入图片描述


4、接口式编程

创建一个接口:

package mybatis.dao;

import mybatis.Employee;

public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
}

将接口与 xml 进行动态绑定(创建一个同名的 xml 文件,即 EmployeeMapper.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="mybatis.dao.EmployeeMapper">

    <!--namespace:命名空间;指定为接口的全类名
        id:唯一标识
        resultType:返回值类型
        #{id}:从传递过来的参数中取出id值-->

    <select id="selectEmp" resultType="mybatis.bean.Employee">
        <!--在这里我们使用了别名,使得字段名和类的属性名相同-->
        select id,last_name lastName,email,gender from tbl_employee where id = #{id}
    </select>

    <!--
        public Employee getEmpById(Integer id);
    -->
    <select id="getEmpById" resultType="mybatis.bean.Employee">
        <!--在这里我们使用了别名,使得字段名和类的属性名相同-->
        select id,last_name lastName,email,gender from tbl_employee where id = #{id}
    </select>
</mapper>

在这个 xml 文件中进行动态绑定的步骤:

  1. namespace:命名空间;指定为接口的全类名:mybatis.dao.EmployeeMapper
  2. <select> 标签的 id 属性设置为接口中查询方法的方法名,把查询方法和 sql 进行动态绑定。

测试代码:

public SqlSessionFactory getSqlSessionFactory() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    return new SqlSessionFactoryBuilder().build(inputStream);
}

@Test
public void test2() throws IOException {
    //1、获取sqlSessionFactory对象
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

    //2、获取sqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();

    try {
        //3、获取接口的实现类对象
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);

        Employee employee = mapper.getEmpById(1);

        System.out.println(mapper.getClass());//class com.sun.proxy.$Proxy9代理对象
        System.out.println(employee);
        /*
        DEBUG 12-21 20:48:52,233 ==>  Preparing: select id,last_name lastName,email,gender from tbl_employee where id = ?  (BaseJdbcLogger.java:137) 
        DEBUG 12-21 20:48:52,282 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:137) 
        DEBUG 12-21 20:48:52,322 <==      Total: 1  (BaseJdbcLogger.java:137) 
        class com.sun.proxy.$Proxy9
        Employee{id=1, lastname='tom', email='tom@qq.com', gender='0'}
        */
    }finally {
        sqlSession.close();
    }
}

5、总结

  1. 接口式编程

    • 原生:xxDao ====> xxDaoImpl

      创建一个 xxDao 接口,接口中定义操作数据库的方法;
      接着为其创建一个 xxDaoImpl 的实现类,具体实现操作数据库的方法

    • mybatis:xxMapper ====> xxMapper.xml

      创建一个 xxMapper 的接口,其中定义操作数据库的方法;
      接着创建一个 xxMapper.xml 配置文件,其中使用 namdespace 动态绑定接口文件,使用 <select> 将其中的 sql 语句动态绑定接口中的方法

  2. SqlSession 代表和数据库的一次会话,用完必须关闭;

  3. SqlSession 和 connection 一样都是非线程安全,每次使用都应该去获取新的对象;

  4. xxMapper 接口没有实现类,但是 mybatis 会为这个接口生成一个代理对象;

    (将接口和 xml 进行绑定)

    EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class);

  5. 两个重要的配置文件:

    mybatis 的全局配置文件:包含数据库连接池信息,事务管理器信息等…系统运行环境信息;

    sql 映射文件:保存了每一个 sql 语句的映射信息:将 sql 抽取出来。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值