MyBatis——配置文件模板、使用工具类对数据库操作、MyBatis代理

1.配置文件模板

配置文件模板主要是针对在日常学习中,有重复的代码文件,可以设置成模板来方便我们使用

 

 

 

 2.使用工具类来实现对数据库的相关操作

首先我们先来看看MyBatis实现对数据库操作的基本代码

 //1.定义mybatis主配值文件的位置,从路径开始的相对位置
        String confid = "mybatis.xml";
        //2.读取主配置文件,使用mybatis框架中的Resources类
        InputStream inputStream = Resources.getResourceAsStream(confid);
        //3.创建SqlSessionFactory对象,使用SqlSessionFactoryBuidler类
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //4.获取SqlSession 对象
        SqlSession session=factory.openSession();
        //5.指定要执行的sql语句的id  sql的id=namespace+“.”+select|update|insert|delete标签的id属性值
        String sqlId="com.lhy.dao.studentDao.selectstudentId";
        //6.通过sqlSession的方法执行sql语句
        //Student student=session.selectOne(sqlId);
        Student student=session.selectOne(sqlId,10009);
        System.out.println("使用Mybatis查询一个学生:"+student);
        //7.关闭sqlSession对象
        session.close();

相关注解已经标明,我们在测试类中,每写一个方法,都要加上这样的几行,让人觉得太麻烦了,而且会造成一定量的代码冗余,所以我们可以将这几行重要的代码封装到一个工具类MyBatisUtil中,在使用的时候直接调用MyBatisUtil类即可。

工具类MyBatisUtil

package com.liuhaiyang.utils;

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;


public class MybatisUtils {
    private static SqlSessionFactory factory=null;
    static {
        String config="mybatis.xml";
        try {
              InputStream  inputstream = Resources.getResourceAsStream(config);
              factory = new SqlSessionFactoryBuilder().build(inputstream);
        } catch (IOException e) {
                e.printStackTrace();
            }
    }
    //创建方法,获取SqlSession对象
    public static SqlSession getSqlSession(){
        SqlSession session=null;
        if(factory!=null){
            session=factory.openSession();  //openSession(true); 表示自动提交
        }
        return session;
    }
}

此时的测试类代码为

      @Test
    public void testSelectById() {
        //1.获取SqlSession
        SqlSession session = MyBatisUtil.getSqlSession();
        //2.指定sqlId
        String sqlId="com.lhy.dao.studentDao.selectstudentId";
        //3.执行SqlSession的方法,表示执行sql语句
        Student student=session.selectOne(sqlId,1009);
        System.out.println("查询的结果===" + student);
        //4.关闭SqlSession对象
        session.close();
    }

这两种方式查询的结果是相同的,工具类能够帮助我们将重复的代码段复用,是我们编写代码效率提高,来看看这个工具类的相关操作。我们首先通过 SqlSession 对象来调用工具类中写好的方法 getSqlSession() (这个方法中已经加载过主配置文件,同时创建好了 SqlSessionFactory 对象)。之后再根据具体的 mapper 文件中的 namespace、id等相关信息,定义好要读取的 sqlId,最终执行就可以了。

3.Mybatis代理 

说到MyBatis代理,一定要提到dao代理,所谓的代理,就是通过MyBatis的相关类和方法帮助我们完成对数据库的相关操作,不必在使用繁琐的步骤完对数据库的操作。下面写个例子来感受一下:

创建一个dao包,包中放的是接口和Mapper.xml文件 。StudentDao接口代码:

package com.liuhaiyang.dao;

import com.liuhaiyang.domain.Student;

import java.util.List;

public interface StudentDao {
    Student selectById(Integer id);

    List<Student> selectStudents();

    int insertStudent(Student student);

}

Mapper.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.liuhaiyang.dao.StudentDao">
    <!--使用insert,uodate,delete,select标签写sql-->
    <!--
   parameterType="java.lang.Integer"
    parameterType:指定dao接口形参的类型
                   这个属性的值可以使用 Java类型的全限定名称或者是mybatis定义的别名
                   可以省略不写
    -->
    <select id="selectById" resultType="com.liuhaiyang.domain.Student">
        select  *  from student where id=#{id}
    </select>
    <select id="selectStudents" resultType="com.liuhaiyang.domain.Student">
        select  *  from student
    </select>
    <insert id="insertStudent" >
        insert into student values (#{id},#{name},#{email},#{age})
    </insert>
</mapper>

MyBatisUtil工具类在上面代码中有,不用变动

测试类

package com.liuhaiyanmg;

import com.liuhaiyang.dao.StudentDao;
import com.liuhaiyang.domain.Student;
import com.liuhaiyang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MyTest {

    @Test//能够单次执
    public void testSelectById(){
        //1.获取sqlsession
        SqlSession session= MybatisUtils.getSqlSession();
        //dao代理帮我们写了String sql="com.liuhaiyang.dao.StudentDao.selectById";
        // 和Student student = session.selectOne(sql, 10001);
        //并且调用帮忙实现接口的方法。
        StudentDao dao=session.getMapper(StudentDao.class);
        //调用接口的实现方法
        Student student=dao.selectById(10009);
        System.out.println("查询结果====>"+student);
        //关闭sqlsession
        session.close();
    }
    @Test
    public void tsetSelectlist(){
        SqlSession session=MybatisUtils.getSqlSession();
        StudentDao dao=session.getMapper(StudentDao.class);
        List<Student> stu=dao.selectStudents();
//        for(Student st:stu)
//            System.out.println(st); 另外一种方式
        stu.forEach(student -> System.out.println(student));  //student->是固定格式  本行代码是循环遍历stu集合
        session.close();
    }
    @Test
    public void testSelectinset(){
        SqlSession session =MybatisUtils.getSqlSession();
        StudentDao dao=session.getMapper(StudentDao.class);
        Student student=new Student(100011,"小红","xiiaohong@qq.com",21);
        int a= dao.insertStudent(student);
        session.commit();
        System.out.println(a);
        session.close();
    }

}

结果截图;

我们在测试类中看到,使用了dao代理比原来的代码还要简练。dao代理帮助我们写了String sql="com.liuhaiyang.dao.StudentDao.selectById";和Student student = session.selectOne(sql, 10001); 提高我们面向对象编程思想。万物皆可对象。

下面来说说MyBatis代理的其他作用

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值