Spring中的Mybatis

what?

  • MyBatis(前身是Ibatis)是一个支持普通SQL查询,存储过程以及高级映射关系的持久层框架。
  • MyBatis框架(也称为ORM Object/Relation Mapping, 对象关系映射框架):ORM是为了解决面向对象与关系型数据库数据类型不匹配的技术,它通过描述Java对象与数据库表之间的映射关系,自动将Java应用程序中的对象持久化到关系型数据库的表中。
    在这里插入图片描述

Hibernate和Mybatis的区别

在这里插入图片描述

Mybatis的工作原理

在这里插入图片描述

  • 读取MyBatis的配置文件mybatis-config.xml,mybatis-config.xml作为mybatis的全局配置文件,,配置了mybatis的运行环境,主要是数据库的连接,
  • 加载映射文件mapper.xml,mapper.xml即SQL映射文件,该文件配置了操作数据库的SQL语句,需要在mybatis-config.xml中加载配置,在mybatsi-config.xml中可以加载配置多个文件,每个文件对应一张数据库中的表
  • 构建会话工厂,通过mybatis_config.xml的配置信息构建SqlSessionFactory
  • 构建SqlSession对象,该会话包括了执行SQl语句的所有的方法,它是由SqlSessionFactory对象常见的。
  • mybatis的底层定义了一个Executor接口来操作数据库,根据SqlSession传递的参数动态的生成需要执行的SQL语句,同时负责查询缓存的维护
  • 在Executor接口的执行方法中,包含了一个MappedStatement类型的参数,该参数用于封装映射信息,也就是映射Sql语句中的id,参数等。Mapper.xml文件中的一个SQL语句就是一个mappedSatement对象,SQL的id就是MappedStatement的id,
  • 输入参数映射,MappedStatement对象会对用户输入的参数进行定义(是什莫类型),在Excutor执行Sql语句之前,mappedStatemnt将封装的参数信息映射到对应的sql语句中。
  • 输出结果映射,在Excutor执行了SQL语句之后,MappedStatement对象会将结果映射到对应的java对象中。

mybatis的查询

log4j.properties

输出日志信息

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.yzb.chapter06=DEBUG
# 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

Customer

在这里插入代码片package com.yzb.chapter06.pojo;
/*
* 客户持久化层
* */
public class Customer {
    private Integer id;
    private String username;
    private String jobs;
    private String 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;
    }

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

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">
<!-- namespace表示命名空间 -->
<mapper namespace="com.yzb.chapter06.mapper.CustomerMapper">
    <!--根据客户编号获取客户信息 -->
    <select id="findCustomerById" parameterType="Integer"
            resultType="com.yzb.chapter06.pojo.Customer">
        select * from t_customer where id = #{id}
    </select>
    <!--根据客户名模糊查询客户信息-->
    <select id="findCustomerByUsername" resultType="com.yzb.chapter06.pojo.Customer" parameterType="String">
        select * from t_customer where username like '%${value}%'
    </select>


</mapper>

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>
    <!--1.配置环境 ,默认的环境id为mysql-->
    <environments default="mysql">
        <!--1.2.配置id为mysql的数据库环境 -->
        <environment id="mysql">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <!--数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                          value="jdbc:mysql://localhost:3306/spring" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <!--2.配置Mapper的位置 -->
    <mappers>
        <mapper resource="com/yzb/chapter06/mapper/CustomerMapper.xml" />
    </mappers>
</configuration>

Test

package com.yzb.chapter06;

import com.yzb.chapter06.pojo.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;


/*
* 入门程序
* */
public class Test {
/*    public static void main(String[] args) throws IOException {
        //读取配置文件
        String resource = "com/yzb/chapter06/mybatis-config.xml";
        //得到文件的输出流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //根据配置文件构建SqlSessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过SqlSessionFactory创建Sqlsession
        SqlSession sqlSession = sessionFactory.openSession();
        //sqlSession执行映射文件中定义的SQL语句,并返回映射结果
        Customer  customer = sqlSession.selectOne("com.yzb.chapter06.mapper.CustomerMapper.findCustomerById", 1);
        //打印输出结果
        System.out.println(customer.toString());
        //关闭SqlSession
        sqlSession.close();
    }*/
    public static void main(String[] args) throws IOException {
        //读取配置文件
        String resource = "com/yzb/chapter06/mybatis-config.xml";
        //得到文件的输出流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //根据配置文件构建SqlSessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过SqlSessionFactory创建Sqlsession
        SqlSession sqlSession = sessionFactory.openSession();
        //sqlSession执行映射文件中定义的SQL语句,并返回映射结果
        List<Customer> customers = sqlSession.selectList("com.yzb.chapter06.mapper.CustomerMapper.findCustomerByUsername", "j");
        //打印输出结果##
        for (Customer customer : customers) {
            System.out.println(customer.toString());
        }
        //关闭SqlSession
        sqlSession.close();
    }
}

mybatis的更新,删除,添加

在上面的代码基础上进行更改。

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">
<!-- namespace表示命名空间 -->
<mapper namespace="com.yzb.chapter06.mapper.CustomerMapper">
    <!--根据客户编号获取客户信息 -->
    <select id="findCustomerById" parameterType="Integer"
            resultType="com.yzb.chapter06.pojo.Customer">
        select * from t_customer where id = #{id}
    </select>
    <!--根据客户名模糊查询客户信息-->
    <select id="findCustomerByUsername" resultType="com.yzb.chapter06.pojo.Customer" parameterType="String">
        /* 如果你输入的值是带有'号的,就会出现错误。*/
        /* select * from t_customer where username like '%${value}%'*/
        /*这样就不怕有错了*/
        select * from t_customer where username like concat('%','#{value}','%')
    </select>
    <!--添加用户信息-->
    <insert id="addCustomer" parameterType="com.yzb.chapter06.pojo.Customer">
        insert into t_customer(username,jobs,phone) values(#{username},#{jobs},#{phone})
    </insert>
    <!--更改用户信息-->
    <update id="updateCustomer" parameterType="com.yzb.chapter06.pojo.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>

Test

package com.yzb.chapter06;

import com.yzb.chapter06.pojo.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;


/*
* 入门程序
* */
public class Test {
    /*
    * 查询用户
    * */
/*    public static void main(String[] args) throws IOException {
        //读取配置文件
        String resource = "com/yzb/chapter06/mybatis-config.xml";
        //得到文件的输出流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //根据配置文件构建SqlSessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过SqlSessionFactory创建Sqlsession
        SqlSession sqlSession = sessionFactory.openSession();
        //sqlSession执行映射文件中定义的SQL语句,并返回映射结果
        Customer  customer = sqlSession.selectOne("com.yzb.chapter06.mapper.CustomerMapper.findCustomerById", 1);
        //打印输出结果
        System.out.println(customer.toString());
        //关闭SqlSession
        sqlSession.close();
    }*/
/*
* 模糊查询用户
* */
  /*  public static void main(String[] args) throws IOException {
        //读取配置文件
        String resource = "com/yzb/chapter06/mybatis-config.xml";
        //得到文件的输出流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //根据配置文件构建SqlSessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过SqlSessionFactory创建Sqlsession
        SqlSession sqlSession = sessionFactory.openSession();
        //sqlSession执行映射文件中定义的SQL语句,并返回映射结果
        List<Customer> customers = sqlSession.selectList("com.yzb.chapter06.mapper.CustomerMapper.findCustomerByUsername", "j");
        //打印输出结果
        for (Customer customer : customers) {
            System.out.println(customer.toString());
        }
        //关闭SqlSession
        sqlSession.close();
    }*/
  /*
  * 添加用户
  * */
/*    public static void main(String[] args) throws IOException {
        //读取配置文件
        String resource = "com/yzb/chapter06/mybatis-config.xml";
        //得到文件的输出流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //根据配置文件构建SqlSessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过SqlSessionFactory创建Sqlsession
        SqlSession sqlSession = sessionFactory.openSession();
        //创建一个Customer对象,并向对象中添加数据
        Customer customer = new Customer();
        customer.setUsername("yue");
        customer.setJobs("147");
        customer.setPhone("147");
        //sqlSession执行映射文件中定义的SQL语句,并返回映射结果
        //第一个参数是Sql语句的id,第二个参数是sql语句执行时要添加的参数
        int count = sqlSession.insert("com.yzb.chapter06.mapper.CustomerMapper.addCustomer", customer);
        if(count>0){
            System.out.println("插入数据成功");
        }else {
            System.out.println("插入数据失败");
        }
        //提交事务,对于曾删改需要提交事务,否则更改不了数据库
        sqlSession.commit();
        //关闭SqlSession
        sqlSession.close();
    }*/
/*
* 修改用户
* */
/*    public static void main(String[] args) throws IOException {
        //读取配置文件
        String resource = "com/yzb/chapter06/mybatis-config.xml";
        //得到文件的输出流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //根据配置文件构建SqlSessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过SqlSessionFactory创建Sqlsession
        SqlSession sqlSession = sessionFactory.openSession();
        //创建一个Customer对象,并向对象中添加数据
        Customer customer = new Customer();
        customer.setId(4);
        customer.setUsername("yue");
        customer.setJobs("369");
        customer.setPhone("369");
        //sqlSession执行映射文件中定义的SQL语句,并返回映射结果
        //第一个参数是Sql语句的id,第二个参数是sql语句执行时要添加的参数
        int update = sqlSession.update("com.yzb.chapter06.mapper.CustomerMapper.updateCustomer", customer);
        if(update>0){
            System.out.println("修改成功");
        }else {
            System.out.println("修改失败");
        }
        //提交事务,对于曾删改需要提交事务,否则更改不了数据库
        sqlSession.commit();
        //关闭SqlSession
        sqlSession.close();
    }*/
/*
* 删除用户
* */
    public static void main(String[] args) throws IOException {
        //读取配置文件
        String resource = "com/yzb/chapter06/mybatis-config.xml";
        //得到文件的输出流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //根据配置文件构建SqlSessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过SqlSessionFactory创建Sqlsession
        SqlSession sqlSession = sessionFactory.openSession();

        //sqlSession执行映射文件中定义的SQL语句,并返回映射结果
        //第一个参数是Sql语句的id,第二个参数是sql语句执行时要添加的参数
        int delete = sqlSession.delete("com.yzb.chapter06.mapper.CustomerMapper.deleteCustomer", 4);
        if(delete>0){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
        //提交事务,对于曾删改需要提交事务,否则更改不了数据库
        sqlSession.commit();
        //关闭SqlSession
        sqlSession.close();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值