MyBatis的工作原理及入门程序

89 篇文章 1 订阅

在这里插入图片描述

(1)读取MyBatis的配置文件。mybatis-config.xml为MyBatis的全局配置文件,用于配置数据库连接信息。

(2)加载映射文件。映射文件即SQL映射文件,该文件中配置了操作数据库的SQL语句,需要在MyBatis配置文件mybatis-config.xml中加载。mybatis-config.xml 文件可以加载多个映射文件,每个文件对应数据库中的一张表。

(3)构造会话工厂。通过MyBatis的环境配置信息构建会话工厂SqlSessionFactory。

(4)创建会话对象。由会话工厂创建SqlSession对象,该对象中包含了执行SQL语句的所有方法。

(5)Executor执行器。MyBatis底层定义了一个Executor接口来操作数据库,它将根据SqlSession传递的参数动态地生成需要执行的SQL语句,同时负责查询缓存的维护。

(6)MappedStatement对象。在Executor接口的执行方法中有一个MappedStatement类型的参数,该参数是对映射信息的封装,用于存储要映射的SQL语句的id、参数等信息。

(7)输入参数映射。输入参数类型可以是Map、List等集合类型,也可以是基本数据类型和POJO类型。输入参数映射过程类似于JDBC对preparedStatement对象设置参数的过程。

(8)输出结果映射。输出结果类型可以是Map、List等集合类型,也可以是基本数据类型和POJO类型。输出结果映射过程类似于JDBC对结果集的解析过程。

MyBatis入门程序

1.查询用户

更具客户编号查询客户信息。

CREATE DATABASE mybatis;//创建名字为mybatis的数据库
use mybatis;//使用mybatis
//创建一个数据表
CREATE TABLE t_customer(
    id int(32) primary key auto_increment,
    username varchar(50),
    jobs varchar(50),
    phone varchar(16)
);

2.创建项目

创建一个java项目,导入mybatis的包,使用mybatis框架只需要在应用程序中引入mybatis的核心包和lib目录中的依赖包即可。

由于mybatis默认使用log4j输出日志信息,所以要查看控制台的输出SQL语句。在项目src下建立log4j.properties文件。编辑后如下:

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

创建包com.itheima.po.在该包下创建持久化类Customer

package com.itheima.po;

public class Customer {
    private Integer id;
    private String username;
    private String jobs;
    private String phone;

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", jobs='" + jobs + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getJobs() {
        return jobs;
    }

    public void setJobs(String jobs) {
        this.jobs = jobs;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

在src目录下,创建com.itheima.mapper包,在包中创建映射文件CustomerMapper.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="com.itheima.mapper.CustomerMapper">
    <select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer">
        select * from t_customer where id = #{id}
    </select>
    <select id="findCustomerByName" parameterType="String" resultType="com.itheima.po.Customer">
        select * from t_customer where username like '%${value}%'
    </select>
    <insert id="addCustomer" parameterType="com.itheima.po.Customer">
        insert into t_customer(username,jobs,phone)
        values(#{username},#{jobs},#{phone})
    </insert>
    <update id="updateCustomer" parameterType="com.itheima.po.Customer">
        update t_customer set
            username=#{username},jobs=#{jobs},phone=#{phone}
            where id=#{id}
    </update>
    <delete id="deleteCustomer" parameterType="Integer">
        delete from t_customer where id=#{id}
    </delete>

</mapper>

在src目录下,创建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="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="用户"/>
                <property name="password" value="密码"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/itheima/mapper/CustomerMapper.xml"/>
    </mappers>
</configuration>

在ssrc目录下,创建com.itheima.test包,在该包下创建测试类MybatisTest

package com.itheima.test;

import com.itheima.po.Customer;
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.List;

import org.junit.Test;
public class MybatisTest {
    @Test
    public void findCustomerByIdTest() throws Exception{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Customer customer = sqlSession.selectOne("com.itheima.mapper"+".CustomerMapper.findCustomerById",1);
        System.out.println(customer.toString());
        sqlSession.close();
    }
    /*
    *根据用户名来模拟查询用户信息列表
     */
    @Test
    public void findCustomerByNameTest() throws Exception {
        //1.读取配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //2.根据配置文件构建SqlSessionfactory
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        //3.通过sqlSessionFactory创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4.SqlSession执行映射文件中定义的SQL,并返回映射结果
        List<Customer> customers = sqlSession.selectList("com.itheima.mapper"
                + ".CustomerMapper.findCustomerByName", "j");
        for (Customer customer : customers) {
            System.out.println(customer);
        }
        //5.关闭SqlSession
        sqlSession.close();
    }
        /*
        *添加用户
         */
    @Test
    public void addCustomerTest () throws Exception{
        //1.读取配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //2.根据配置文件构建SqlSessionfactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.通过sqlSessionFactory创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4.
        Customer customer = new Customer();
        customer.setUsername("rose");
        customer.setJobs("teacher");
        customer.setPhone("1222737282");
        int rows = sqlSession.insert("com.itheima.mapper"+".CustomerMapper.addCustomer",customer);
        if(rows > 0) {
            System.out.println("插入操作执行成功!");
        }
        else
        {
            System.out.println("插入操作执行失败!!");
        }
        sqlSession.commit();
        sqlSession.close();

        }
        /*
        *更新账户
         */
    @Test
    public void updateCustomerTest() throws Exception{
        //1.读取配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //2.根据配置文件构建SqlSessionfactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.通过sqlSessionFactory创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4.
        Customer customer = new Customer();
        customer.setId(4);
        customer.setUsername("joy");
        customer.setJobs("programmer");
        customer.setPhone("112222222222");
        int rows = sqlSession.update("com.itheima.mapper"+".CustomerMapper.addCustomer",customer);
        if(rows > 0) {
            System.out.println("更新操作执行成功!");
        }
        else
        {
            System.out.println("更新操作执行失败!!");
        }
        sqlSession.commit();
        sqlSession.close();
    }
    /*
    *删除客户
     */
    @Test
    public void deleteCustomerTest() throws IOException {
        //1.读取配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //2.根据配置文件构建SqlSessionfactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.通过sqlSessionFactory创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4.SqlSession执行删除操作
        //4.1执行SqlSession的删除方法
        int rows = sqlSession.delete("com.itheima.mapper" + ".CustomerMapper.deleteCustomer", 10);
        if (rows > 0) {
            System.out.println("删除操作执行成功!");
        } else {
            System.out.println("删除操作执行失败!!");
        }
        //4.3提交事务
        sqlSession.commit();
        //5.关闭SqlSession
        sqlSession.close();
    }
}
.CustomerMapper.deleteCustomer", 10);
        if (rows > 0) {
            System.out.println("删除操作执行成功!");
        } else {
            System.out.println("删除操作执行失败!!");
        }
        //4.3提交事务
        sqlSession.commit();
        //5.关闭SqlSession
        sqlSession.close();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值