Mybatis入门之接口代理实现Dao

一、代理方式介绍

  采用Mybatis的代理开发方式实现Dao层的开发,这种方式是一般企业的主流。
  Mapper接口开发方法值需要程序员编写Mapper接口,由Mybatis框架根据接口定义创建接口的动态代理类。Mapper接口开发需要遵循以下规范:

1)Mapper.xml文件中的namespace与mapper接口的全限定名相同。

2)Mapper接口方法名和Mapper.xml中定义的每个statement的id相同**

3)Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同**

4)Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同**

二、编写接口

2.1 新建环境

  1. 新建项目
  2. 添加jar包
  3. 添加实体类

    在这里插入图片描述
    在这里插入图片描述

2.2 编写Mapper接口

package cn.study.mapper;

import cn.study.demo.Student;

import java.util.List;

public interface StudentMapper {

    //查询全部
    public abstract List<Student> selectAll();
}

2.3 编写xml文件

2.3.1 MyBatisConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<!--configuration 核心根标签-->
<configuration>

    <!--引入数据库连接的配置文件-->
    <properties resource="jdbc.properties"/>

    <!--配置LOG4J-->
    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>

    <!--起别名-->
    <typeAliases>
        <typeAlias type="cn.study.demo.Student" alias="student"/>
    </typeAliases>

    <!--environments配置数据库环境,环境可以有多个。default属性指定使用的是哪个-->
    <environments default="mysql">
        <!--environment配置数据库环境  id属性唯一标识-->
        <environment id="mysql">
            <!-- transactionManager事务管理。  type属性,采用JDBC默认的事务-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- dataSource数据源信息   type属性 连接池-->
            <dataSource type="POOLED">
                <!-- property获取数据库连接的配置信息 -->
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>

    <!-- mappers引入映射配置文件 -->
    <mappers>
        <!-- mapper 引入指定的映射配置文件   resource属性指定映射配置文件的名称 -->
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>

2.3.2 StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--
    mapper: 核心根标签
    namespace属性: 名称空间
 -->
<mapper namespace="cn.study.mapper.StudentMapper">

    <select id="selectAll" resultType="student">
        SELECT * FROM student
    </select>

</mapper>

2.4 编写service

package cn.study.service;

import cn.study.demo.Student;
import cn.study.mapper.StudentMapper;
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 StudentService {
    static SqlSession sqlSession = null;
    static InputStream is = null;
    static{
        //1.加载核心配置文件
        try {
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

            //3.通过工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Student> selectAll() {
        List<Student> list = null;
        try{
            //4.获取StudentMapper接口的实现类对象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // StudentMapper mapper = new StudentMapperImpl();

            //5.通过实现类对象调用方法,接收结果
            list = mapper.selectAll();

        } catch (Exception e) {

        } finally {
            //6.释放资源
            if(sqlSession != null) {
                sqlSession.close();
            }
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //7.返回结果
        return list;
    }

}

三、测试方式

//创建业务层对象
    private StudentService service = new StudentService();

    @Test
    public void test1(){
        List<Student> students = service.selectAll();
        for (Student stu : students) {
            System.out.println(stu);
        }
    }

四、源码分析

4.1 动态代理

  通过动态代理开发模式,只编写一个接口,不写实现类,通过getMappe()方法最终获取到MapperPoxy代理对象,然后执行功能,而这个代理对象正是MyBatis使用了JDK的动态代理技术,帮助我么实现类对象。从而可以进行相关的持久化操作。

4.2 方法执行

  动态代理实现类对象在执行方法的时候最终调用了mapperMethod.execute() 方法,这个方法通过switch语句根据操作类型来判断新增、修改、删除、查询操作,最后一步回到了MyBatis最原生的SqlSession方式在执行增删改查。

五、总结

  接口代理方式可以让我们只编写接口即可,而实现类对象由 MyBatis 生成。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值