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

//答案是用JDK动态代理实现的

下午想到了一个JAVA中的一个很基础的问题,java中接口是不能实例化的,想到这点,让我想起了mybatis框架中的mapper的用法,我们有用mapper时,全都是没有实现类的,只有一个mapper接口,而我们在调用的时候,通过spring注入到适当的service或其他类中就可以用了,那么它的原理是什么呢,mapper调用时又是在哪里进行了实现的呢?

带着这个问题,我重新复习了下mybatis的用法,为了测试方便,我在mysql上建了一个user表,并插入了3条记录,并写了一个简单的mybatis例子,代码如下:

 
  1. package com.haiyang.learn.mybaits;

  2.  
  3. import com.haiyang.learn.mybaits.mapper.UserMapper;

  4. import com.haiyang.learn.mybaits.pojo.User;

  5. import org.apache.ibatis.datasource.pooled.PooledDataSource;

  6. import org.apache.ibatis.mapping.Environment;

  7. import org.apache.ibatis.session.Configuration;

  8. import org.apache.ibatis.session.SqlSession;

  9. import org.apache.ibatis.session.SqlSessionFactory;

  10. import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;

  11. import org.apache.ibatis.transaction.TransactionFactory;

  12. import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

  13. import javax.sql.DataSource;

  14. import java.util.List;

  15.  
  16. /**

  17. * author: haiyangp

  18. * date: 2017/8/19

  19. * desc: Main

  20. */

  21. public class MybatisMain {

  22. private String driverName = "com.mysql.jdbc.Driver";

  23. private String url = "jdbc:mysql://127.0.0.1:3306/test";

  24. private String username = "root";

  25. private String password = "root";

  26.  
  27.  
  28. public static void main(String[] args) {

  29. MybatisMain mybatis =new MybatisMain();

  30. SqlSessionFactory sqlSessionFactory = mybatis.initMybatis();

  31. SqlSession sqlSession = sqlSessionFactory.openSession();

  32. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

  33. List<User> userList = userMapper.getAllUser();

  34. for (User userItem : userList) {

  35. System.out.println(userItem);

  36. }

  37. }

  38.  
  39. /**

  40. * 初始化mybatis,并返回sqlSessionFactory

  41. */

  42. private SqlSessionFactory initMybatis() {

  43. DataSource dataSource = initDataSourceWithReturn();

  44. TransactionFactory transactionFactory = new JdbcTransactionFactory();

  45. Environment environment = new Environment("justForTest", transactionFactory, dataSource);

  46. Configuration configuration = new Configuration(environment);

  47. configuration.getTypeAliasRegistry().registerAlias("user", User.class);//注册别名

  48. configuration.addMapper(UserMapper.class);//添加mapper

  49. return new DefaultSqlSessionFactory(configuration);

  50. }

  51.  
  52.  
  53. /**

  54. * 初始化并获取dataSource

  55. *

  56. * @return DataSource

  57. */

  58. private DataSource initDataSourceWithReturn() {

  59. PooledDataSource dataSource = new PooledDataSource();

  60. dataSource.setUrl(url);

  61. dataSource.setDriver(driverName);

  62. dataSource.setUsername(username);

  63. dataSource.setPassword(password);

  64. return dataSource;

  65. }

  66.  
  67. }

以及UserMapper.java

 
  1. package com.haiyang.learn.mybaits.mapper;

  2.  
  3. import com.haiyang.learn.mybaits.pojo.User;

  4. import org.apache.ibatis.annotations.Select;

  5.  
  6. import java.util.List;

  7.  
  8. public interface UserMapper {

  9. /**

  10. * 获取所有user

  11. *

  12. * @return 所有user

  13. */

  14.  
  15. @Select(value = "select * from user")

  16. List<User> getAllUser();

  17.  
  18. /**

  19. * 根据用户id获取用户信息

  20. *

  21. * @param id 用户ID

  22. * @return 用户

  23. */

  24. @Select(value = "select * from user where id = #{id}")

  25. User getUserById(Integer id);

  26. }

User.java

 
  1. public class User {

  2. private Integer id;

  3. private String username;

  4. private String password;

  5. //get 和 set方法

  6. }

为了方便,并没有配置xml等信息了,主要是通过 sqlSession的getMapper方法获取出了UserMapper对象,并通过它查询出了对应的user表的数据

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
 List<User> userList = userMapper.getAllUser();

执行结果如下:

 
  1. 2017-08-19 22:51:36,384 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.

  2. 2017-08-19 22:51:36,385 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.

  3. 2017-08-19 22:51:36,385 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.

  4. 2017-08-19 22:51:36,385 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.

  5. 2017-08-19 22:53:04,746 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Openning JDBC Connection

  6. 2017-08-19 22:53:04,964 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 1472465.

  7. 2017-08-19 22:53:04,966 [main] DEBUG com.haiyang.learn.mybaits.mapper.UserMapper.getAllUser - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@1677d1]

  8. 2017-08-19 22:53:04,966 [main] DEBUG com.haiyang.learn.mybaits.mapper.UserMapper.getAllUser - ==> Preparing: select * from user

  9. 2017-08-19 22:53:04,988 [main] DEBUG com.haiyang.learn.mybaits.mapper.UserMapper.getAllUser - ==> Parameters:

  10. User{id=1, username='jack', password='123456'}

  11. User{id=2, username='tom', password='654321'}

  12. 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动态代理实现接口

猜你喜欢

转载自blog.csdn.net/f45056231p/article/details/81738530