深入理解MyBatis-Spring中间件(spring/mybatis整合)

转:http://blog.csdn.net/fqz_hacker/article/details/53485833

Mybatis-Spring

1.应用
mybatis是比较常用的数据库中间件,我们都知道我们来看看怎么在spring中使用mybatis,假设有用户表User,包含四个字段 (id,name,sex,mobile),在Spring中使用mybatis操作User表非常简单,这里使用的是mybatis-spring 1.3.0,首先定义接口,
[java] view plain copy
 
  1. public interface UserMapper {  
  2.     int createUser(@Param("user") User user);  
  3. }  
然后,定义对应的mybatis xml文件,
[java] view plain copy
 
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <!--PUBLIC后面跟着的可以用于验证文档结构的 DTD 系统标识符和公共标识符。-->  
  3. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4. <mapper namespace="com.fqz.mybatis.dao.UserMapper"><!--namespace是必须的,指向对应的java interface,要把包名写全,此例中为com.fqz.mybatis.dao.UserMapper -->  
  5.     <resultMap id="User" type="User">  
  6.         <id property="id" column="id"/>  
  7.         <result property="name" column="name"/>  
  8.         <result property="sex" column="sex"/>  
  9.         <result property="mobile" column="mobile"/>  
  10.     </resultMap>  
  11.   
  12.     <insert id="createUser" parameterType="User" useGeneratedKeys="true" keyColumn="id" keyProperty="user.id">  
  13.         INSERT INTO  
  14.         User  
  15.         (name,sex,mobile)  
  16.         VALUES  
  17.         (#{user.name},#{user.sex},#{user.mobile})  
  18.     </insert>  
  19.   
  20. </mapper>  
紧接着,添加配置文件,命名为spring-dao.mxl,
[java] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:context="http://www.springframework.org/schema/context"  
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.                            http://www.springframework.org/schema/beans/spring-beans.xsd  
  7.                            http://www.springframework.org/schema/context  
  8.                            http://www.springframework.org/schema/context/spring-context.xsd">  
  9.   
  10.     <context:component-scan base-package="com.fqz.mybatis"/>  
  11.   
  12.     <!-- Data Source -->  
  13.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
  14.         <property name="driverClass" value="com.mysql.jdbc.Driver"/>  
  15.         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/fqz"/>  
  16.         <property name="user" value="root"/>  
  17.         <property name="password" value="abcd1234"/>  
  18.         <!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数  -->  
  19.         <property name="acquireIncrement" value="5"></property>  
  20.         <!-- 初始连接池大小 -->  
  21.         <property name="initialPoolSize" value="10"></property>  
  22.         <!-- 连接池中连接最小个数 -->  
  23.         <property name="minPoolSize" value="5"></property>  
  24.         <!-- 连接池中连接最大个数 -->  
  25.         <property name="maxPoolSize" value="20"></property>  
  26.     </bean>  
  27.   
  28.     <!-- 扫描对应的XML Mapper -->  
  29.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  30.         <!-- 数据源 -->  
  31.         <property name="dataSource" ref="dataSource"></property>  
  32.         <!-- 别名,它一般对应我们的实体类所在的包,这个时候会自动取对应包中不包括包名的简单类名作为包括包名的别名。多个package之间可以用逗号或者分号等来进行分隔。 -->  
  33.         <property name="typeAliasesPackage" value="com.fqz.mybatis.entity"></property>  
  34.         <!-- sql映射文件路径,它表示我们的Mapper文件存放的位置,当我们的Mapper文件跟对应的Mapper接口处于同一位置的时候可以不用指定该属性的值。 -->  
  35.         <property name="mapperLocations" value="classpath*:mybatis/*.xml"></property>  
  36.     </bean>  
  37.   
  38.     <!-- 扫描对应的Java Mapper -->  
  39.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  40.         <property name="basePackage" value="com.fqz.mybatis.dao"/>  
  41.         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>  
  42.     </bean>  
  43.   
  44. </beans>  
定义服务UserService接口和实现类,此处没给出UserService接口定义,
[java] view plain copy
 
  1. @Service  
  2. public class UserServiceImpl implements UserService {  
  3.     @Resource  
  4.     UserMapper userMapper;  
  5.     public int createUser(UserDTO userDTO) {  
  6.         User user = new User();  
  7.         BeanUtils.copyProperties(userDTO,user,new String[]{"id"});  
  8.         int row = userMapper.createUser(user);//插入返回值为作用的记录数;生成的主键已经被赋值到user对象上  
  9.         if(row >= 1)  
  10.             return user.getId();  
  11.         return -1;  
  12.     }  
  13.   
  14.     public UserDTO getUserById(Integer id) {  
  15.         return null;  
  16.     }  
  17. }  

完成接口定义、mybatis xml定义和配置文件,就可以直接使用接口来操作数据库,
[java] view plain copy
 
  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations = {"classpath*:spring/spring-*.xml"})  
  3. public class TestUser{  
  4.     private static UserService userService;  
  5.   
  6.     @BeforeClass  
  7.     public static void beforeClass(){  
  8.         ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-dao.xml");  
  9.         userService = context.getBean(UserService.class);  
  10.     }  
  11.     @Test  
  12.     public void testCreatUser(){  
  13.         UserDTO userDTO = new UserDTO();  
  14.         userDTO.setName("your name");  
  15.         userDTO.setSex(true);  
  16.         userDTO.setMobile("12134232211");  
  17.         Integer userId = userService.createUser(userDTO);  
  18.         System.out.println(userId);  
  19.         System.out.println(userDTO.getId());  
  20.     }  
  21.   
  22. }  
2. 原理
从UserServiceImpl实现类中可以看出,服务类直接使用的UserMapper接口来操作数据库,而UserMapper接口没有对应的实现 类,这一切都是由spring-mybatis库通过动态代理实现的,接下来分析下它的实现原理,先由SqlSessionFactoryBean生成 SQLSessionFactory和并扫描接口,为接口生成动态代理
1. SqlSessionFactoryBean配置
它的主要作用是扫描sql xml文件,查看源码,
[java] view plain copy
 
  1. public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean  
SqlSessionFactoryBean 实现了FactoryBean和InitializingBean,因此会首先执行afterPropertiesSet()方法,然后根据 getObject()方法返回的对象生产Spring Bean,这里生产的是SqlSessionFactory类型的对象,在afterPropertiesSet方法中,执行了 buildSqlSessionFactory方法来初始化SqlSessionFactory对象,来看看其中的一段,
[java] view plain copy
 
  1. if (!isEmpty(this.mapperLocations)) {  
  2.       for (Resource mapperLocation : this.mapperLocations) {  
  3.         if (mapperLocation == null) {  
  4.           continue;  
  5.         }  
  6.   
  7.         try {  
  8.           XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),  
  9.               configuration, mapperLocation.toString(), configuration.getSqlFragments());  
  10.           xmlMapperBuilder.parse();  
  11.         }   
进入XmlMapperBuilder.parse方法,
[java] view plain copy
 
  1. private void bindMapperForNamespace() {  
  2.     String namespace = builderAssistant.getCurrentNamespace();  
  3.     if (namespace != null) {  
  4.       Class<?> boundType = null;  
  5.       try {  
  6.         boundType = Resources.classForName(namespace);  
  7.       } catch (ClassNotFoundException e) {  
  8.         //ignore, bound type is not required  
  9.       }  
  10.       if (boundType != null) {  
  11.         if (!configuration.hasMapper(boundType)) {  
  12.           // Spring may not know the real resource name so we set a flag  
  13.           // to prevent loading again this resource from the mapper interface  
  14.           // look at MapperAnnotationBuilder#loadXmlResource  
  15.           configuration.addLoadedResource("namespace:" + namespace);  
  16.           configuration.addMapper(boundType);  
  17.         }  
  18.       }  
  19.     }  
  20.   }  
namespace指定了mybatis dao接口的路径,通过configuration.addMapper(boundType)将接口的动态代理委托给MapperRegistry,MapperRegistry中通过MapperFactory生成动态代理,
[java] view plain copy
 
  1. public <T> T getMapper(Class<T> type, SqlSession sqlSession) {  
  2.     final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);  
  3.     if (mapperProxyFactory == null) {  
  4.       throw new BindingException("Type " + type + " is not known to the MapperRegistry.");  
  5.     }  
  6.     try {  
  7.       return mapperProxyFactory.newInstance(sqlSession);  
  8.     } catch (Exception e) {  
  9.       throw new BindingException("Error getting mapper instance. Cause: " + e, e);  
  10.     }  
  11.   }  
  12.     
  13.   public <T> boolean hasMapper(Class<T> type) {  
  14.     return knownMappers.containsKey(type);  
  15.   }  
  16.   
  17.   public <T> void addMapper(Class<T> type) {  
  18.     if (type.isInterface()) {  
  19.       if (hasMapper(type)) {  
  20.         throw new BindingException("Type " + type + " is already known to the MapperRegistry.");  
  21.       }  
  22.       boolean loadCompleted = false;  
  23.       try {  
  24.         knownMappers.put(type, new MapperProxyFactory<T>(type));  
  25.         // It's important that the type is added before the parser is run  
  26.         // otherwise the binding may automatically be attempted by the  
  27.         // mapper parser. If the type is already known, it won't try.  
  28.         MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);  
  29.         parser.parse();  
  30.         loadCompleted = true;  
  31.       } finally {  
  32.         if (!loadCompleted) {  
  33.           knownMappers.remove(type);  
  34.         }  
  35.       }  
  36.     }  
  37.   }  
MapperProxyFactory中使用Proxy.newProxyInstance来生成动态代理
[java] view plain copy
 
  1. protected T newInstance(MapperProxy<T> mapperProxy) {  
  2.    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);  
  3.  }  
  4.   
  5.  public T newInstance(SqlSession sqlSession) {  
  6.    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);  
  7.    return newInstance(mapperProxy);  
  8.  }  
MapperProxy为动态代理的处理类,实际上将SqlSession操作db的过程封装在了MapperMethod类中,
[java] view plain copy
 
  1. public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {  
  2.     this.sqlSession = sqlSession;  
  3.     this.mapperInterface = mapperInterface;  
  4.     this.methodCache = methodCache;  
  5.   }  
  6.   
  7.   @Override  
  8.   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
  9.     if (Object.class.equals(method.getDeclaringClass())) {  
  10.       try {  
  11.         return method.invoke(this, args);  
  12.       } catch (Throwable t) {  
  13.         throw ExceptionUtil.unwrapThrowable(t);  
  14.       }  
  15.     }  
  16.     final MapperMethod mapperMethod = cachedMapperMethod(method);  
  17.     return mapperMethod.execute(sqlSession, args);  
  18.   }  
简单看下结构,


总结,SqlSessionFactoryBean实际上对应的是SqlSessionFactory类,它会扫描sql xml文件,并对接口创建动态代理,将接口类的Class和动态代理关系保存在SqlSessionFactory中,这仅仅是完成了动态代理的生成,而 动态代理在哪里被使用到,怎么使用,这些都是由MapperScannerConfigurer完成,接下来看看 MapperScannerConfigurer都做了些什么?

2. MapperScannerConfigurer 
从开始的配置文件可以看出,MapperScannerConfigurer依赖于SqlSessionFactoryBean和Mapper 接口所在package,之前也说过SqlSessionFactoryBean实际上对应的是SqlSessionFactory,它可以提供 Mapper接口的动态代理类,而Mapper所在package提供了扫描的路径,在扫描过程中,会把每个Mapper接口对应到一个 MapperFactoryBean,MapperFactoryBean实际上对应的是动态代理类,这一切也就说通了,下面来看看源码,

MapperScannerConfigurer实现了BeanDefinitionRegistryPostProcessor接口,因此会在bean factory初始化的时候,被调用到,调用的方法为postProcessBeanDefinitionRegistry,因此看看 postProcessBeanDefinitionRegistry的源码,
[java] view plain copy
 
  1. public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {  
  2.     if (this.processPropertyPlaceHolders) {  
  3.       processPropertyPlaceHolders();  
  4.     }  
  5.   
  6.     ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);  
  7.     scanner.setAddToConfig(this.addToConfig);  
  8.     scanner.setAnnotationClass(this.annotationClass);  
  9.     scanner.setMarkerInterface(this.markerInterface);  
  10.     scanner.setSqlSessionFactory(this.sqlSessionFactory);  
  11.     scanner.setSqlSessionTemplate(this.sqlSessionTemplate);  
  12.     scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);  
  13.     scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);  
  14.     scanner.setResourceLoader(this.applicationContext);  
  15.     scanner.setBeanNameGenerator(this.nameGenerator);  
  16.     scanner.registerFilters();  
  17.     scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));  
  18.   }  
调用了ClassPathMapperScanner的scan()方法,
[java] view plain copy
 
  1. public int scan(String... basePackages) {  
  2.         int beanCountAtScanStart = this.registry.getBeanDefinitionCount();  
  3.   
  4.         doScan(basePackages);  
  5.   
  6.         // Register annotation config processors, if necessary.  
  7.         if (this.includeAnnotationConfig) {  
  8.             AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);  
  9.         }  
  10.   
  11.         return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);  
  12.     }  
scan 方法又调用了doScan方法,看看ClassPathMapperScanner的doScan方法,Spring会首先把需要实例化的bean加载的 BeanDefinitionHolder的集合中,doScan方法,就是添加mybatis mapper接口的bean定义到BeanDefinitionHolder集合,
[java] view plain copy
 
  1. public Set<BeanDefinitionHolder> doScan(String... basePackages) {  
  2.     Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);  
  3.   
  4.     if (beanDefinitions.isEmpty()) {  
  5.       logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");  
  6.     } else {  
  7.       processBeanDefinitions(beanDefinitions);  
  8.     }  
  9.   
  10.     return beanDefinitions;  
  11.   }  
  12.   
  13.   private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {  
  14.     GenericBeanDefinition definition;  
  15.     for (BeanDefinitionHolder holder : beanDefinitions) {  
  16.       definition = (GenericBeanDefinition) holder.getBeanDefinition();  
  17.   
  18.       if (logger.isDebugEnabled()) {  
  19.         logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName()   
  20.           + "' and '" + definition.getBeanClassName() + "' mapperInterface");  
  21.       }  
  22.   
  23.       // the mapper interface is the original class of the bean  
  24.       // but, the actual class of the bean is MapperFactoryBean  
  25.       definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59  
  26.       definition.setBeanClass(this.mapperFactoryBean.getClass());//将其bean Class类型设置为mapperFactoryBean,放入BeanDefinitions  
  27.   
  28.       definition.getPropertyValues().add("addToConfig", this.addToConfig);  
  29.   
  30.       boolean explicitFactoryUsed = false;  
  31.       if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {  
  32.         definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));  
  33.         explicitFactoryUsed = true;  
  34.       } else if (this.sqlSessionFactory != null) {  
  35.         definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);  
  36.         explicitFactoryUsed = true;  
  37.       }  
  38.   
  39.       if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {  
  40.         if (explicitFactoryUsed) {  
  41.           logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");  
  42.         }  
  43.         definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));  
  44.         explicitFactoryUsed = true;  
  45.       } else if (this.sqlSessionTemplate != null) {  
  46.         if (explicitFactoryUsed) {  
  47.           logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");  
  48.         }  
  49.         definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);  
  50.         explicitFactoryUsed = true;  
  51.       }  
  52.   
  53.       if (!explicitFactoryUsed) {  
  54.         if (logger.isDebugEnabled()) {  
  55.           logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");  
  56.         }  
  57.         definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);  
  58.       }  
  59.     }  
  60.   }  
那MapperFactoryBean究竟又做了什么呢,看源码,
[java] view plain copy
 
  1. MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean  
通过集成SqlSessionDaoSupport获得SqlSessionFactory,通过实现FactoryBean,生产动态代理对象,
[java] view plain copy
 
  1. @Override  
  2.   public T getObject() throws Exception {  
  3.     return getSqlSession().getMapper(this.mapperInterface);  
  4.   }  
一 切到这里就已经很显而易见了,Mapper接口对应的Spring Bean实际上就是getSqlSession().getMapper(this.mapperInterface)返回的动态代理,每次装配 Mapper接口时,就相当于装配了此接口对应的动态代理,这样就顺利成章的被代理成功了。
原文地址:https://www.cnblogs.com/zhanglijun/p/8405501.html