//答案是用JDK动态代理实现的
下午想到了一个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动态代理实现接口