mybatis中的Mapper实现---动态代理

java主流的开发框架中基本都使用了反射机制,这种机制无非就是通过分析字符串来实现动态生成类,动态装配类,也没有什么可神秘的。

已经用了一段时间mybatis了,抽空也读了一下mybatis的源代码,今天大致解析一下mybatis框架中的核心部分源码。

mybatis有一个特点就是dao类不需要实现,直接使用接口就能完成对应方法的功能,实现这个特性使用了java中的动态代理,也就是执行的时候mybatis框架中的代理类代替用户实现了相应方法。当然这其中还会有一堆xml文件的解析,一堆辅助类的装配。

一、先看看mybatis是怎么使用的吧,为了更清楚的看到mybatis的使用过程,我们不使用spring框架对齐整合,而是单独用mybaris掩饰。

新建一个类

Address类

package testmybatis;


import java.io.Serializable;

public class Address  implements Serializable {
    private Integer id;

    private String usertel;

    private String useraddress;

    private Integer userid;

    private String province;

    private String city;

    private String area;

    private String username;

    private String postcode;

    private Integer isdefault;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsertel() {
        return usertel;
    }

    public void setUsertel(String usertel) {
        this.usertel = usertel == null ? null : usertel.trim();
    }

    public String getUseraddress() {
        return useraddress;
    }

    public void setUseraddress(String useraddress) {
        this.useraddress = useraddress == null ? null : useraddress.trim();
    }

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province == null ? null : province.trim();
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city == null ? null : city.trim();
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area == null ? null : area.trim();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPostcode() {
        return postcode;
    }

    public void setPostcode(String postcode) {
        this.postcode = postcode == null ? null : postcode.trim();
    }

    public Integer getIsdefault() {
        return isdefault;
    }

    public void setIsdefault(Integer isdefault) {
        this.isdefault = isdefault;
    }
}

  新建AddressMapper接口

package testmybatis;


public interface AddressMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Address record);

    int insertSelective(Address record);

    Address selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Address record);

    int updateByPrimaryKey(Address record);
}

  新建mybatis配置文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC" />
      <dataSource type="POOLED">
	 <property name="driver" value="com.mysql.jdbc.Driver" />  
         <property name="url" value="jdbc:mysql://127.0.0.1:3306/db?useUnicode=true&characterEncoding=UTF-8" />  
         <property name="username" value="root" />  
         <property name="password" value="root" />
      </dataSource>
    </environment>
  </environments>
    <mappers>
       <mapper  resource="testmybatis/AddressMapper.xml"/>
    </mappers>
</configuration>

  新建测试类

package testmybatis;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class TestMyBatis {
	public static void main(String[] args) throws IOException {
		String path="testmybatis/cfg.xml";
		InputStream in=Resources.getResourceAsStream(path);
		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();  
        SqlSessionFactory factory = builder.build(in); 
        SqlSession session=factory.openSession();
        AddressMapper mapper=session.getMapper(AddressMapper.class);
        Address address=mapper.selectByPrimaryKey(2);
        System.out.println(address);
	}
}

  我们发现主要步骤就是先根据一个配置文件build一个SqlSessionFactory,然后再生成一个SqlSession,然后从session中取出一个mapper,这个mapper其实已经不是原来的mapper,而是经过代理的类。

二、先看看Mapper代码对象的生成过程

DefaultSqlSession.getMapp()方法最终会调用MapperRegistry.getMapper()方法。

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {  
   //这个MapperProxyFactory是调用addMapper方法时加到knownMappers中的,  
   final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);  
   if (mapperProxyFactory == null)  
     //说明这个Mapper接口没有注册  
     throw new BindingException("Type " + type + " is not known to the MapperRegistry.");  
   try {  
      //生成一个MapperProxy对象  
     return mapperProxyFactory.newInstance(sqlSession);  
   } catch (Exception e) {  
     throw new BindingException("Error getting mapper instance. Cause: " + e, e);  
   }  
 } 

  下面是MapperProxyFactory的newInstance方法

public T newInstance(SqlSession sqlSession) {  
    //创建一个Mapperproxy对象,这个方法实现了JDK动态代理中的InvocationHandler接口  
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);  
    return newInstance(mapperProxy);  
  }  
  
protected T newInstance(MapperProxy<T> mapperProxy) {  
    //mapperInterface,说明Mapper接口被代理了,这样子返回的对象就是Mapper接口的子类,方法被调用时会被mapperProxy拦截,也就是执行mapperProxy.invoke()方法  
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);  
  }

 

MapperProxy

public class MapperProxy<T> implements InvocationHandler, Serializable {  
  
  private static final long serialVersionUID = -6424540398559729838L;  
  private final SqlSession sqlSession;  
  
  //Mapper接口  
  private final Class<T> mapperInterface;  
  
  //Mapper接口中的每个方法都会生成一个MapperMethod对象, methodCache维护着他们的对应关系  
  //这个methodCache是在MapperProxyFactory中持有的,MapperProxyFactory又是在Configuration中持有的  
  //所以每个Mapper接口类对应的MapperProxyFactory和methodCache在整个应用中是共享的,一般只会有一个实例  
  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;  
  }  
  
  
  //这里会拦截Mapper接口(UserDao)的所有方法  
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
    //如果是Object中定义的方法,直接执行。如toString(),hashCode()等待。  
    if (Object.class.equals(method.getDeclaringClass())) {  
      try {  
        return method.invoke(this, args);  
      } catch (Throwable t) {  
        throw ExceptionUtil.unwrapThrowable(t);  
      }  
    }  
    //其他Mapper接口定义的方法交由mapperMethod来执行。  
    final MapperMethod mapperMethod = cachedMapperMethod(method);  
    return mapperMethod.execute(sqlSession, args);  
  }  
  
  private MapperMethod cachedMapperMethod(Method method) {  
    MapperMethod mapperMethod = methodCache.get(method);  
    if (mapperMethod == null) {  
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());  
      methodCache.put(method, mapperMethod);  
    }  
    return mapperMethod;  
  }  
  
}  

  

在看MapperMethod

//所有Mapper接口中方法被调用里,都会执行这个方法.这里实际上是调用SqlSession中的相关方法,  
public Object execute(SqlSession sqlSession, Object[] args) {  
  Object result;  
  //判断这个方法被注解里的Sql类型  
  if (SqlCommandType.INSERT == command.getType()) {  
    //执行insert  
    Object param = method.convertArgsToSqlCommandParam(args);  
    result = rowCountResult(sqlSession.insert(command.getName(), param));  
  } else if (SqlCommandType.UPDATE == command.getType()) {  
    //执行update  
    Object param = method.convertArgsToSqlCommandParam(args);  
    result = rowCountResult(sqlSession.update(command.getName(), param));  
  } else if (SqlCommandType.DELETE == command.getType()) {  
    /delete  
    Object param = method.convertArgsToSqlCommandParam(args);  
    result = rowCountResult(sqlSession.delete(command.getName(), param));  
  } else if (SqlCommandType.SELECT == command.getType()) {  
    //select ,查询  
    if (method.returnsVoid() && method.hasResultHandler()) {  
      //没有返回值,并且有ResultHandler的情况  
      executeWithResultHandler(sqlSession, args);  
      result = null;  
    } else if (method.returnsMany()) {  
      //返回一个List  
      result = executeForMany(sqlSession, args);  
    } else if (method.returnsMap()) {  
      //返回一个Map  
      result = executeForMap(sqlSession, args);  
    } else {  
      //返回一个对象  
      Object param = method.convertArgsToSqlCommandParam(args);  
      result = sqlSession.selectOne(command.getName(), param);  
    }  
  } else {  
    throw new BindingException("Unknown execution method for: " + command.getName());  
  }  
  if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {  
    throw new BindingException("Mapper method '" + command.getName()   
        + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");  
  }  
  return result;  
} 

  

 

小结

  1. 在Mybatis提供的编程接口中,开发人员只需要定义好Mapper接口,开发人员无需去实现。Mybatis会利用JDK的动态代理实现 Mapper接口。
  2. 在Mybatis中,每个Mapper接口都会对应一个MapperProxyFactory对象实例,这个对应关系在Configuration.mapperRegistry.knownMappers中。
  3. 当getMapper()方法被调用时,Mybatis会找到相对应的MapperProxyFactory对象实例,利用这个工厂来创建一个jdk动态代理对象,是这个Mapper接口的实现类,当Mapper定义的方法被调用时,会调用MapperProxy来处理。
  4. MapperProxy会根据方法找到对应的MapperMethod对象来实现这次调用。
  5. MapperMethod对应会读取方法中的注解,从Configuration中找到相对应的MappedStatement对象,再执行
posted @ 2017-07-25 09:59  涛涛的笔记  阅读(355)  评论(0)    收藏  举报