MyBatis框架学习(2)----MyBatis接口式编程

来源:互联网 发布:阿里云域名解析 编辑:程序博客网 时间:2024/06/05 09:35

1、之前MyBatis的hello_world的认识

在之前的学到的MyBatis框架中的第一个hello_world的时候,我是在测试单元里调用了MyBatis的API中的selectone函数,其中的参数可以指定sql映射文件中的sql查询语句的ID,然后通过这个id来找到具体的查询语句,用图来看:

<1.>先看sql映射文件,以下是sql映射文件中的sql查询语句的id和结果的类型resultType

<2.>再来看看我写的测试单元的内容,其中前两步:创建SqlSessionFactory和获取sqlsession是必做的两步,下面中的try中的内容就是调用了MyBatis的API中的selectone函数,其中的参数可以指定sql映射文件中的sql查询语句的ID,然后通过这个id来找到具体的查询语句

@Test    public void test() throws IOException {        //创建SqlSessionFactory        String resource = "mybatis_conf.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        //获取sqlsession实例        SqlSession sqlsession = sqlSessionFactory.openSession();        //第一个参数是sql语句的唯一标识        //第二个参数是执行sql要用的参数        try{        Student student = sqlsession.selectOne("com.bean.Student.mapper.selectStudent", 1);        System.out.println(student);        }finally{            sqlsession.close();        }    }

这个hello_world是最简单的一个MyBatis实例,但是我们要是这样开发的话,在测试的时候,调用API时参数也很麻烦,而且其中selectone函数的第二个参数是对象类型的,我们不只可以传入int类型的id,也可以传入“abc”这样的字段,那在开发的时候会遇到不知的错误,在MyBatis的官方文档中,有一种接口式编程的方法来同样的去调用,而且我们也不用再去调用selectone的API

2、接口式编程

<1.>创建一个接口类,我们取名为StudentMapper,内容如下:只声明一个返回值类型为Student的函数。

package com.dao;import com.bean.Student;public interface StudentMapper {    public Student getStuById(int id);}

<2.>修改sql映射文件的内容:
将sql映射文件的namespace内容修改为接口类的全称,将sql映射文件的select标签中的id修改为接口中声明的函数,这样就实现了接口和sql映射文件的绑定。

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.dao.StudentMapper"><!-- 名称空间:与接口所在的类全称绑定id:唯一标识标签#{id}:从传递过来的参数中取出id--><select id="getStuById" resultType="com.bean.Student">select id,last_name lastname,email,gender from tbl_stu where id = #{id}</select></mapper>

<3.>再看看单元测试部分该怎么用:

@Test    public void test01() throws IOException{        //1、获取SqlSessionFactory        String resource = "mybatis_conf.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        //2、获取sqlsession        SqlSession sqlsession = sqlSessionFactory.openSession();        //3、获取接口的实现类对象        StudentMapper stumap = sqlsession.getMapper(StudentMapper.class);        try{        Student stu = stumap.getStuById(1);        System.out.println(stu);        }finally{            sqlsession.close();        }    }

其中第三步之后就是和之前的hello_world的区别,就是具体的去通过某个接口来去调用sql映射文件中的查询语句

原创粉丝点击