为什么mybatis的mapper没有实现类(原理探究)

昨天晚上坐公交回家时,在公交车上看见了一个男生和一个女生,年龄跟我差不多大的样子,他们俩在公交车前面面对面地坐着,那个男生坐在位置上看坐在他对面的那个女生,一直傻傻地看了的很长一段时间,若有所思的样子,从他俩的表情与眼神上来看,应该是一段时间没有见面的情侣,想必他们那时的心情应该是激动又开心的。公交到站时,那个男生帮那个女生提起了她的行李包,他俩走下公交,我坐在公交上注意着车窗外的夜色,也注意着他们,看着竟让我生心羡慕,羡慕他们能在魔都在一起。这让我想起了前些年过年时,电视节目会问许多不同的对象一个问题:“幸福是什么”,我想这个问题每个人在不同的时刻都会有着自己不同的答案。要是在昨天那个时刻问他们幸福是什么,估计他们会说他们那时就是幸福的。哈哈。

-------------------------------------------------------------------------------------------分割线----------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------分割线----------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------分割线----------------------------------------------------------------------------------------------------------


下午想到了一个JAVA中的一个很基础的问题, java中接口是不能实例化的,想到这点,让我想起了mybatis框架中的mapper的用法,我们有用mapper时,全都是没有实现类的,只有一个mapper接口,而我们在调用的时候,通过spring注入到适当的service或其他类中就可以用了,那么它的原理是什么呢,mapper调用时又是在哪里进行了实现的呢?
带着这个问题,我重新复习了下mybatis的用法,为了测试方便,我在mysql上建了一个user表,并插入了3条记录,并写了一个简单的mybatis例子,代码如下:
package com.haiyang.learn.mybaits;

import com.haiyang.learn.mybaits.mapper.UserMapper;
import com.haiyang.learn.mybaits.pojo.User;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import javax.sql.DataSource;
import java.util.List;

/**
 * author: haiyangp
 * date:  2017/8/19
 * desc: Main
 */
public class MybatisMain {
    private String driverName = "com.mysql.jdbc.Driver";
    private String url = "jdbc:mysql://127.0.0.1:3306/test";
    private String username = "root";
    private String password = "root";


    public static void main(String[] args) {
        MybatisMain mybatis =new MybatisMain();
        SqlSessionFactory sqlSessionFactory = mybatis.initMybatis();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getAllUser();
        for (User userItem : userList) {
            System.out.println(userItem);
        }
    }

    /**
     * 初始化mybatis,并返回sqlSessionFactory
     */
    private SqlSessionFactory initMybatis() {
        DataSource dataSource = initDataSourceWithReturn();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("justForTest", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.getTypeAliasRegistry().registerAlias("user", User.class);//注册别名
        configuration.addMapper(UserMapper.class);//添加mapper
        return new DefaultSqlSessionFactory(configuration);
    }


    /**
     * 初始化并获取dataSource
     *
     * @return DataSource
     */
    private DataSource initDataSourceWithReturn() {
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setUrl(url);
        dataSource.setDriver(driverName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

}
以及UserMapper.java
package com.haiyang.learn.mybaits.mapper;

import com.haiyang.learn.mybaits.pojo.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper {
    /**
     * 获取所有user
     *
     * @return 所有user
     */

    @Select(value = "select * from user")
    List<User> getAllUser();

    /**
     * 根据用户id获取用户信息
     *
     * @param id 用户ID
     * @return 用户
     */
    @Select(value = "select * from user where id = #{id}")
    User getUserById(Integer id);
}
User.java
public class User {
    private Integer id;
    private String username;
    private String password;
    //get 和 set方法
}

为了方便,并没有配置xml等信息了,主要是通过 sqlSession的getMapper方法获取出了UserMapper对象,并通过它查询出了对应的user表的数据
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
 List<User> userList = userMapper.getAllUser();
执行结果如下:
2017-08-19 22:51:36,384 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2017-08-19 22:51:36,385 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2017-08-19 22:51:36,385 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2017-08-19 22:51:36,385 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2017-08-19 22:53:04,746 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Openning JDBC Connection
2017-08-19 22:53:04,964 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 1472465.
2017-08-19 22:53:04,966 [main] DEBUG com.haiyang.learn.mybaits.mapper.UserMapper.getAllUser - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@1677d1]
2017-08-19 22:53:04,966 [main] DEBUG com.haiyang.learn.mybaits.mapper.UserMapper.getAllUser - ==>  Preparing: select * from user 
2017-08-19 22:53:04,988 [main] DEBUG com.haiyang.learn.mybaits.mapper.UserMapper.getAllUser - ==> Parameters: 
User{id=1, username='jack', password='123456'}
User{id=2, username='tom', password='654321'}
User{id=3, username='lili', password='666666'}

那么回到原话题,UserMapper并没有实现类,它是怎么就把数据给查询出来的呢?
通过debug跟踪了下getMapper这个方法,看到了关键代码:
public class MapperProxyFactory<T> {
    private final Class<T> mapperInterface;
    private Map<Method, MapperMethod> methodCache = new ConcurrentHashMap();

    public MapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public Class<T> getMapperInterface() {
        return this.mapperInterface;
    }

    public Map<Method, MapperMethod> getMethodCache() {
        return this.methodCache;
    }

    protected T newInstance(MapperProxy<T> mapperProxy) {
        return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
    }

    public T newInstance(SqlSession sqlSession) {
        MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
        return this.newInstance(mapperProxy);
    }
}
代码运行到了标红色的部分,即:
 return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
看到这里,我想大家都知道了答案了,我们获取mapper,它返回给了我们一个Proxy。用过JDK动态代理的看到Proxy.newProxyInstance这句一定感到非常的熟悉吧。原来mapper是通过动态代码来实现的,newProxyInstance的第三个参数即为代理执行器的handler了,它传入的是一个mapperProxy对象
通过Proxy.newProxyInstance方法源码也可以看到如下注释信息:
* @return  a proxy instance with the specified invocation handler of a
*          proxy class that is defined by the specified class loader
*          and that implements the specified interfaces
再通过查看mapperProxy的代码:
public class MapperProxy<T> implements InvocationHandler, Serializable {
    private static final long serialVersionUID = -6424540398559729838L;
    private final SqlSession sqlSession;
    private final Class<T> mapperInterface;
    private final Map<Method, MapperMethod> methodCache;

    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        } else {
            MapperMethod mapperMethod = this.cachedMapperMethod(method);
            return mapperMethod.execute(this.sqlSession, args);
        }
    }

    private MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = (MapperMethod)this.methodCache.get(method);
        if (mapperMethod == null) {
            mapperMethod = new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration());
            this.methodCache.put(method, mapperMethod);
        }

        return mapperMethod;
    }
}


那么我们执行sqlSession.getMapper(UserMapper.class)这句代码最终返回的应该就是一个由jdk动态代理生成的代理类
当执行userMapper.getAllUser()方法时,最终执行的也就是 mapperMethod.execute(this.sqlSession,args)的代码
所以回到原问题,为什么mybatis的mapper没有实现类呢?原因是因为 它采用了:Java动态代理实现接口


评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水中加点糖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值