博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring中的Mybatis
阅读量:3965 次
发布时间:2019-05-24

本文共 10528 字,大约阅读时间需要 35 分钟。

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 configurationlog4j.rootLogger=ERROR, stdout# MyBatis logging configuration...log4j.logger.com.yzb.chapter06=DEBUG# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.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

mybatis-config.xml

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
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

insert into t_customer(username,jobs,phone) values(#{username},#{jobs},#{phone})
update t_customer set username= #{username} ,jobs = #{jobs} ,phone = #{phone} where id = #{id}
delete from t_customer where id = #{id}

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
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(); }}

转载地址:http://czwki.baihongyu.com/

你可能感兴趣的文章
去掉文件名中的路径
查看>>
Spring Batch Step 流程
查看>>
动态代理
查看>>
如何写出高效的正则表达式
查看>>
多个 ZooKeeper 服务器的例子
查看>>
正则表达式
查看>>
Java I/O
查看>>
序列化
查看>>
Perl 精萃
查看>>
Perl 简介
查看>>
Perl 注释
查看>>
数据类型之标量
查看>>
调试 Perl 脚本
查看>>
增强的for循环语句
查看>>
方法的可变参数
查看>>
静态导入
查看>>
java 泛型
查看>>
控制结构
查看>>
标准输入输出
查看>>
运算符
查看>>