mybatis 中的注解


正常使用 mybatis时的写法:

AddressMapper mapper = session.getMapper(AddressMapper.class);  (第一句)

Address address = mapper.queryById(101); (第二句)

Q1mapper 如何 通过  sqlmap-XXX.xml 调用到 mysql

第一句 实际返回的 是MapperProxy

实际执行时:会执行到MapperProxy的invoke方法:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  try {
    if (Object.class.equals(method.getDeclaringClass())) {
      return method.invoke(this, args);
    } else if (isDefaultMethod(method)) {
      return invokeDefaultMethod(proxy, method, args);
    }
  } catch (Throwable t) {
    throw ExceptionUtil.unwrapThrowable(t);
  }
  final MapperMethod mapperMethod = cachedMapperMethod(method);
  return mapperMethod.execute(sqlSession, args);
}

MapperMethod 下面

一个是:SqlCommand

String statementName = mapperInterface.getName() + "." + method.getName();

MappedStatement ms = null;

if (configuration.hasStatement(statementName)) {

  ms = configuration.getMappedStatement(statementName);

}


name = ms.getId();

type = ms.getSqlCommandType();



另一个是:

MethodSignature

用于说明方法的一些信息,主要有返回信息


最终 方法执行时:execute(SqlSession sqlSession, Object[] args)

会执行:

Object param = method.convertArgsToSqlCommandParam(args);

result = sqlSession.selectOne(command.getName(), param);




Address address = session.selectOne("org.mybatis.example.AddressMapper.queryById", 101);

statement 标识: sqlmap-XXX.xml 下的namespace. id


/**

 * Retrieve a single row mapped from the statement key and parameter.

 * @param <T> the returned object type

 * @param statement Unique identifier matching the statement to use.

 * @param parameter A parameter object to pass to the statement.

 * @return Mapped object

 */

<T> T selectOne(String statement, Object parameter);


底层基于

MappedStatement ms = configuration.getMappedStatement(statement);

MyBatis框架会把每一个节点(如:select节点、delete节点)生成一个MappedStatement类。


executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);


## Q2 mybatisspring集成 后 发生了什么?

集成后 XXXDAO  只要有接口就可以, 连实现都不用写了。

也就是框架帮我们做了

AddressMapper mapper = session.getMapper(AddressMapper.class); 

这一句。

调用时直接 调用所需方法即可。


 从MapperScannerConfigurer 开始

*   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
*       <property name="basePackage" value="org.mybatis.spring.sample.mapper" />
*       <!-- optional unless there are multiple session factories defined -->
*       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
*   </bean>


public class MapperScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware {
 
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
  if (this.processPropertyPlaceHolders) {
    processPropertyPlaceHolders();
  }

  ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
  scanner.setAddToConfig(this.addToConfig);
  scanner.setAnnotationClass(this.annotationClass);
  scanner.setMarkerInterface(this.markerInterface);
  scanner.setSqlSessionFactory(this.sqlSessionFactory);
  scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
  scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
  scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
  scanner.setResourceLoader(this.applicationContext);
  scanner.setBeanNameGenerator(this.nameGenerator);
  scanner.registerFilters();
  scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}

在Bean注册到容器之后, 实例化 Bean 之前 扫描basePakage 下的接口。 将其 转换为MapperFactoryBean


## 2 MapperFactoryBean

public abstract class DaoSupport implements InitializingBean {

   /** Logger available to subclasses */
   protected final Log logger = LogFactory.getLog(getClass());


   @Override
   public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException {
      // Let abstract subclasses check their configuration.
      checkDaoConfig();

      // Let concrete implementations initialize themselves.
      try {
         initDao();
      }
      catch (Exception ex) {
         throw new BeanInitializationException("Initialization of DAO failed", ex);
      }
   }

 

## Mybatis中的

public <T> void addMapper(Class<T> type) {
  mapperRegistry.addMapper(type);
}
public <T> void addMapper(Class<T> type) {
  if (type.isInterface()) {
    if (hasMapper(type)) {
      throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
    }
    boolean loadCompleted = false;
    try {
      knownMappers.put(type, new MapperProxyFactory<T>(type));
      // It's important that the type is added before the parser is run
      // otherwise the binding may automatically be attempted by the
      // mapper parser. If the type is already known, it won't try.
下面两行是关键:
      MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
      parser.parse();
      loadCompleted = true;
    } finally {
      if (!loadCompleted) {
        knownMappers.remove(type);
      }
    }
  }
}
public void parse() {
  String resource = type.toString();
  if (!configuration.isResourceLoaded(resource)) {
    loadXmlResource();
    configuration.addLoadedResource(resource);
    assistant.setCurrentNamespace(type.getName());
    parseCache();
    parseCacheRef();
    Method[] methods = type.getMethods();
    for (Method method : methods) {
      try {
        // issue #237
        if (!method.isBridge()) {
          parseStatement(method);
        }
      } catch (IncompleteElementException e) {
        configuration.addIncompleteMethod(new MethodResolver(this, method));
      }
    }
  }
  parsePendingMethods();
}

以CacheNamespace注解解析为例:

private void parseCache() {
  CacheNamespace cacheDomain = type.getAnnotation(CacheNamespace.class);
  if (cacheDomain != null) {
    Integer size = cacheDomain.size() == 0 ? null : cacheDomain.size();
    Long flushInterval = cacheDomain.flushInterval() == 0 ? null : cacheDomain.flushInterval();
    Properties props = convertToProperties(cacheDomain.properties());
    assistant.useNewCache(cacheDomain.implementation(), cacheDomain.eviction(), flushInterval, size, cacheDomain.readWrite(), cacheDomain.blocking(), props);
  }
}

## 涉及到的 Spring 知识点

### 1 spring容器、Bean配置信息、Bean 实现类 和应用程序 4者之间的关系


### 2 spring中处理bean的具体过程




### 3 Spring钩子方法和钩子接口的使用详解

https://www.jianshu.com/p/e22b9fef311c

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
/***********************基本描述**********************************/ 0、根据表可以单独生成javaBean后缀可以自定义 1、工具本身是非常简单的,每个人都能做就是使用模板替换生成相应文件 2、工具主要针对SpringMvc+Mybatis注解+Mysql生成对象,dao、sqlDao、interface、实现接口 3、根据表生成Excel 4、生成成功后倒入到自己对应的项目,然后Ctrl+Shipt+O(Eclipse快速倒入包)实现 5、里面因为运用的是注解,所以很多包我就没有提供了因为这些都是很基础的东西,不会的同学可以去网上查看搭建Mybatis注解 6、生成了些什么,具体主要是对单表的增、删、改、查(分页) /********************************/ /********************************/ /*************完全免费***********/ /********************************/ /********************************/ 如果大家喜欢可以再给我提其他功能,有时间我加上 /*********************************************************************************/ 模板介绍: MySql.Data.dll :连接Mysql基本dl我们的的驱动。 foxjava.exe :直接运行程序 xml : Excel文件夹 ##### TemplateXml.xml 根据数据库对应表生成字段描述,生成后最好用WPS打开,然后重新另存为office认识的Excel template : 文件生成模板(非常重要的不能修改) ##### BasePojo.template 所有基础表对象都要继承,方便序列化(系统自动生成) ##### Pager.template 分页对象 (系统自动生成) ##### dao.template 数据库接口Dao(mybatis接口方式,在方法上写sql,复杂的使用sqlProvider) ##### daoSqlProvider.template 复杂sql提供者 ##### service.template 对外开放的接口 ##### serviceImpl.template 实现开放接口,基本数据操作逻辑 /*********************************************************************************/

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值