spring的mybatis整合笔记(二)

MyBatis详解:spring和mybatis整合 毕竟工作也这么久了 ,除了途虎一轮,也七七八八面试了不少大厂,像阿里、饿了么、美团、滴滴这些面试过程就不一一写在这篇文章上了。我会整理一份详细的面试过程及大家想知道的一些问题细节毕竟工作也这么久了 ,除了途虎一轮,也七七八八面试了不少大厂,像阿里、饿了么、美团、滴滴这些面试过程就不一一写在这篇文章上了。我会整理一份详细的面试过程及大家想知道的一些问题细节。 阅读详情

spring在和mybatis整合时,有两个主要的配置项;

一是sqlSessionFactory的配置,在这个配置里会配置数据库连接池,mapper的xml的路径,比如

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(boneCPDataSource());
        // 配置mapper的扫描,找到所有的mapper.xml映射文件
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml");
        factoryBean.setMapperLocations(resources);
        return factoryBean;
    }

    @Bean(destroyMethod="close")
    public BoneCPDataSource boneCPDataSource(){
        //配置数据库连接池对象
        BoneCPDataSource boneCPDataSource=new BoneCPDataSource();
        boneCPDataSource.setDriverClass("com.mysql.jdbc.Driver");
        boneCPDataSource.setUsername("root");
        boneCPDataSource.setPassword("root");
        boneCPDataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/mytest?serverTimezone=GMT%2B7");
        return boneCPDataSource;
    }

二是mapper类路径的配置,这个路径用一个注解就可以了,在启动的配置类里添加

@MapperScan("com.cn.spring.mybatis.mapper")

此处,我们先看下sqlSessionFactory都做了哪些事

     1、说下SqlSessionFactoryBean和SqlSessionFactory的不同。SqlSessionFactoryBean实现了FactoryBean的接口,我们都知道在创建spring的bean时,有一种方式就是实现此接口。所以SqlSessionFactoryBean和SqlSessionFactory本质上是一样的。

    2、SqlSessionFactoryBean还实现了InitializingBean接口,这个是在spring中bean的生命周期中被回调的,具体是在bean初始化完之后回调InitializingBean的afterPropertiesSet方法,就是下面这个方法


  /**
   * {@inheritDoc}
   */
  @Override
  public void afterPropertiesSet() throws Exception {
    notNull(dataSource, "Property 'dataSource' is required");
    notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
    state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
        "Property 'configuration' and 'configLocation' can not specified with together");

    this.sqlSessionFactory = buildSqlSessionFactory();
  }

3、上面的这个方法,主要是调用了buildSqlSessionFactory()这个方法。这个方法里有很多配置属性的解析,主要是配置的

configLocation里的XML的属性。当然这次我们比较关心mapper.xml的解析,所以暂时先放过它们,看下mapper的解析。
 targetConfiguration.setEnvironment(new Environment(this.environment,
        this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory,
        this.dataSource));

    if (this.mapperLocations != null) {
      if (this.mapperLocations.length == 0) {
        LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found.");
      } else {
        for (Resource mapperLocation : this.mapperLocations) {
          if (mapperLocation == null) {
            continue;
          }
          try {
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
            xmlMapperBuilder.parse();
          } catch (Exception e) {
            throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
          } finally {
            ErrorContext.instance().reset();
          }
          LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
        }
      }
    } else {
      LOGGER.debug(() -> "Property 'mapperLocations' was not specified.");
    }

4、上面的主要是读取了配置了mapperLocations下的文件。然后遍历解析。调用的方法是xmlMapperBuilder.parse();我们看下这个方法的实现

  public void parse() {
    if (!configuration.isResourceLoaded(resource)) {
      configurationElement(parser.evalNode("/mapper"));
      configuration.addLoadedResource(resource);
      bindMapperForNamespace();
    }

    //解析resultMap
    parsePendingResultMaps();
    //解析cacheref
    parsePendingCacheRefs();
    //解析statements
    parsePendingStatements();
  }

这个方法里,主要看bindMapperForNamespace();这个是注册所有mapper的映射类

  private void bindMapperForNamespace() {
    String namespace = builderAssistant.getCurrentNamespace();
    if (namespace != null) {
      Class<?> boundType = null;
      try {
        boundType = Resources.classForName(namespace);
      } catch (ClassNotFoundException e) {
        //ignore, bound type is not required
      }
      if (boundType != null) {
        if (!configuration.hasMapper(boundType)) {
          // Spring may not know the real resource name so we set a flag
          // to prevent loading again this resource from the mapper interface
          // look at MapperAnnotationBuilder#loadXmlResource
          configuration.addLoadedResource("namespace:" + namespace);
          configuration.addMapper(boundType);
        }
      }
    }
  }

最终是注册到了一个map里,

  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<>(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);
        }
      }
    }
  }

这个map是knownMappers,记住这个map,后期会用到的,至此sqlSessionFactory在初始化阶段的工作基本完成。

 

二,我们再看下@MapperScan都做了哪些事

   1、在这个注解里引入了另一个组件@Import(MapperScannerRegistrar.class),这个也是整合spring的惯用套路。

   2、MapperScannerRegistrar,实现了ImportBeanDefinitionRegistrar,接口,这个也是注册bean的一个常用方法。可以实现

registerBeanDefinitions这个方法,然后在此方法里注册bean。看下它注册了什么bean
 @Override
  public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    AnnotationAttributes mapperScanAttrs = AnnotationAttributes
        .fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));
    if (mapperScanAttrs != null) {
      registerBeanDefinitions(importingClassMetadata, mapperScanAttrs, registry,
          generateBaseBeanName(importingClassMetadata, 0));
    }
  }

  void registerBeanDefinitions(AnnotationMetadata annoMeta, AnnotationAttributes annoAttrs,
      BeanDefinitionRegistry registry, String beanName) {
	//其它代码删除了,只留了这一行,因为MapperScannerConfigurer是接下来的最重要的一步
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);

    registry.registerBeanDefinition(beanName, builder.getBeanDefinition());

  }

可以看到这个类注册了MapperScannerConfigurer类,从名字,也可以看出这个类,主要是用来扫描mapper的类的。MapperScannerConfigurer实现了BeanDefinitionRegistryPostProcessor接口,这也是spring生命周期中,比较重要的一个后置处理器。是在beanFactory初始完之后调用的。此处可以对bean容器进行修改,包括添加自己的bean组件。

而mybatis也是在这个后置处理器里添加自己的mapper组件的。看下他在postProcessBeanDefinitionRegistry这个方法里,扫描并注册了所有的mapper类。

  @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.setMapperFactoryBeanClass(this.mapperFactoryBeanClass);
    if (StringUtils.hasText(lazyInitialization)) {
      scanner.setLazyInitialization(Boolean.valueOf(lazyInitialization));
    }
    scanner.registerFilters();
    scanner.scan(
        StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
  }

3、接下来看下ClassPathMapperScanner,这个扫描类,他继承了spring的扫描类ClassPathBeanDefinitionScanner,重写了它的doScan方法。

  @Override
  public Set<BeanDefinitionHolder> doScan(String... basePackages) {
    Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);

    if (beanDefinitions.isEmpty()) {
      LOGGER.warn(() -> "No MyBatis mapper was found in '" + Arrays.toString(basePackages)
          + "' package. Please check your configuration.");
    } else {
      processBeanDefinitions(beanDefinitions);
    }

    return beanDefinitions;
  }

 

4、这里mybatis也是用了spring的扫描功能,然后调用了processBeanDefinitions这个方法,来处理自己的逻辑,看下这个方法的实现,方法进行了一些删减。

private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
    GenericBeanDefinition definition;
    for (BeanDefinitionHolder holder : beanDefinitions) {
      definition = (GenericBeanDefinition) holder.getBeanDefinition();
      String beanClassName = definition.getBeanClassName();
      LOGGER.debug(() -> "Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + beanClassName
          + "' mapperInterface");

      // the mapper interface is the original class of the bean
      // but, the actual class of the bean is MapperFactoryBean
	  //1、注意此处,选择了只有一个参数的构造方法,
      definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName); // issue #59
	  //2、注意此处,把原来的mapper的类的类型修改了,统一改成了MapperFactoryBean这个类
      definition.setBeanClass(this.mapperFactoryBeanClass);

      definition.getPropertyValues().add("addToConfig", this.addToConfig);

      if (!explicitFactoryUsed) {
        LOGGER.debug(() -> "Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
		//3、注意此处,类的注入方法修改成了AUTOWIRE_BY_TYPE,此时只要有set方法,就会实现按类型进行spring的注入
        definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
      }
	  //4、注意此处,lazyInitialization为false,在初始化时,进行赋值的
      definition.setLazyInit(lazyInitialization);
    }
  }

此处把mapper的类统一修改成了MapperFactoryBean,我们看下它的实现

public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T>

1)、它继承了SqlSessionDaoSupport,这个类里有下面这个方法,所以可以完成sqlSessionFactory的自动注入(可以看到上面代码第3点的说明)及sqlSessionTemplate的创建。

  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    if (this.sqlSessionTemplate == null || sqlSessionFactory != this.sqlSessionTemplate.getSqlSessionFactory()) {
      this.sqlSessionTemplate = createSqlSessionTemplate(sqlSessionFactory);
    }
  }

2)、实现了FactoryBean接口,这个接口上面说过,是注册bean的一个常用方法,当获取bean时,会调用这个的getObect方法,现在看下它的getObject方法。

  /**
   * {@inheritDoc}
   */
  @Override
  public T getObject() throws Exception {
    return getSqlSession().getMapper(this.mapperInterface);
  }

这个是从那里获取的呢?我们找下根源,根据调用路径找到了下面的类,就是下面的 getMapper这个方法


public class MapperRegistry {

  private final Configuration config;
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

  public MapperRegistry(Configuration config) {
    this.config = config;
  }

  @SuppressWarnings("unchecked")
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

//删除了多余的代码


}

1)、从这里我们看到了熟悉的knownMappers 这个就是刚才在解析SqlSessionFactoryBean时,最后mapper.xml里信息存储的地方,现在在获取mapper类信息时,也最终到了这里, 从这里也就实现了mapper.xml和mapper类的汇聚。

2)、再接下来调用了mapperProxyFactory.newInstance(sqlSession);来返回对象,我们再看下这个方法

public class MapperProxyFactory<T> {

  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<>();

  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }

  public Class<T> getMapperInterface() {
    return mapperInterface;
  }

  public Map<Method, MapperMethod> getMethodCache() {
    return methodCache;
  }

  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

}

这个类的代码很少,都是干货。这个代码里,我们可以看到newInstance返回的是一个代码里,而代理方式就是jdk自带的动态代理的实现。这是返回的就是一个代理对象。

我们看下这个动态代码的调用的 invoke方法。

  @Override
  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 (method.isDefault()) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

 1)、final MapperMethod mapperMethod = cachedMapperMethod(method);是获取mapper.xml里的解析出来的方法,

2)、mapperMethod.execute(sqlSession, args)调用并返回结果。

手动整合mybatis和spring框架 阅读详情

相关推荐

Mybatis与Spring的整合

10.1 整合环境搭建 Spring和MyBatis的整合主要涉及准备所需的JAR包和编写配置文件,下面将详细介绍。 10.1.1 准备所需的JAR包 要实现MyBatis与Spring的整合,需要这两个框架相关的JAR包,除此之外,还需要其他的JAR包来配合使用。 1.所需Spring框架的JAR包 Spring框架所需要准备的JAR包共10个,其中包括4个核心模块JAR、AOP开发使用的JAR、JDBC和事务的JAR(其中核心容器依赖的commons-logging的JAR在MyBatis框架的lib包

m0_46741750的博客 3873

JDBC(mysql)显式设置serverTimezone的原因和方法

jdbc时区设置原因和方法【参、自】

autumn9909的博客 3979

OPC DCOM详细配置方法 - 不关防火墙不换登陆用户

1. 前言   OPC DCOM的设置是实现跨网络OPC通信的基础,现有的一些OPC DCOM配置教程虽然讲解了如何配置DCOM,但没有讲清楚为什么要这么做,而且各个教程涉及的配置方法也不尽相同。   为了彻底搞清楚OPC DCOM的配置过程,我重新做了两台机器的系统,一台是Windows 7 32位,一台是Windows 10 64位,并且重零开始完整的测试了正常运行OPC DCOM所需的最少的...

steventian72的博客 3万+

mysql版本升级导致的时区问题

在美国从东向西分别为东部时间(EST)(西五区时间)、中部时间(CST)(西六区时间)、山地时间(MST)(西七区时间)、太平洋时间(西部时间)(PST)(西八区时间)、阿拉斯加时间(AKST)(西九区时间)和夏威夷时间(HST)(西十区时间)从东向西分别为东部时间(EST)(西五区时间)、中部时间(CST)(西六区时间)、山地时间(MST)(西七区时间)、太平洋时间(西部时间)(PST)(西八区时间)。会有两个 2020-11-01 01:00:00~2020-11-01 02:00:00区间的时间。

cclovezbf的博客 6025

【Mac+CLion+STM32+JLink】从零到一:在macOS上构建高效STM32开发与调试工作流

本文详细介绍了在macOS上使用CLion、STM32CubeMX和JLink搭建高效STM32开发与调试工作流的完整指南。从环境准备、CLion深度配置到STM32CubeMX工程实战,再到JLink烧录避坑和串口调试技巧,帮助开发者快速掌握Mac平台下的嵌入式开发全流程。

weixin_28278377的博客 256

ArcGIS 10.2.2自带Python 2.7.5环境配置全攻略:从pip安装到gdal、arcpy调用

本文详细指导如何在ArcGIS 10.2.2自带的Python 2.7.5环境中进行高效配置。核心内容包括安装pip包管理器、部署gdal等关键地理数据处理库,并确保arcpy模块的无缝调用。通过解决路径配置与PyCharm集成问题,帮助用户在此经典环境中构建稳定、兼容的地理信息自动化工作流,有效连接ArcGIS桌面功能与Python脚本编程。

moon9的博客 770

serverTimezone时区设置

jdbc:mysql://localhost:3306/hospital?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8

未系上弦月 1万+

防反接电路、防倒灌电路、过流保护和ESP相关知识

1.开关电源给负载供电, 如果负载是电池或者其他感性负载(比如像 电机 有线圈 当电源突然断掉时 会产生感应电动势)时, 当220V断掉的时候,可能会出现 电池反向给开关电源 的 输出端 供电,导致开关电源的一些莫名损坏。2.系统在不同的 输出电压 之间 切换时,会存在高压电压倒灌到低压电压源中。例如:系统 有两个电源供电 比如 一个电池 一个 充电器 充电器的电压一般会高于电池 如果没有防倒灌的电路 可能充电器的电压会直接倒灌给电池 造成电池的损坏。

a_black_的博客 1万+

mysql 加了serverTimezone=GMT%2B8,还是差了8小时

mysql 加了serverTimezone=GMT%2B8,还是差了8小时_L'Étranger的博客-优快云博客_servertimezone=gmt+8

qq_41867611的博客 2055

【TELEMAC V8P4】TELEMAC-2D 用户手册核心概念与应用场景速览

本文深入解析了TELEMAC-2D水动力模型的核心概念与应用。作为基于二维浅水方程的开源数值模拟工具,TELEMAC-2D广泛应用于河流动力学、洪水演进、污染物输运及泥沙运动模拟。文章结合用户手册与实战经验,详细拆解了其理论框架、关键物理过程(如湍流模型、干湿网格处理),并提供了从模型搭建、文件配置到典型场景(如工程评估、污染应急、洪水模拟)的实用指南,帮助用户快速掌握这一强大工具。

weixin_29200741的博客 166

2022年全国职业院校技能大赛网络系统管理赛项模块A:网络构建(样题5)-网络部分解析-附详细代码

2022年全国职业院校技能大赛网络系统管理赛项模块A:网络构建(样题5)-网络部分解析-附详细代码

bfq05234214的博客 424

mysql8.0配置serverTimezone,否则时区报错

jdbc:mysql://localhost:3306/ssm?serverTimezone=GMT%2B8&amp;useSSL=false 在xml和class中“&是读不出的,正确写法将“&”转义“&” 但是如果使用properties文件来配置就不能使用转义,否则解析错误 jdbc:mysql://localhost:3306/ssm?serverTime...

pcb_run的博客 1万+

学Simulink--基于新能源与储能系统的场景实例:压缩空气储能(CAES)系统热力学建模

本文介绍了使用Simulink对压缩空气储能(CAES)系统进行热力学建模的详细流程。重点讲解了系统各模块的设计方法,包括压缩机、储气装置、膨胀机和热交换器等核心组件的参数设置与计算模型。文章还提供了控制策略设计和仿真运行的具体步骤,通过建立MATLAB函数计算关键参数变化,并分析了系统性能评估指标。该建模方法可用于验证CAES系统的设计有效性,并为优化储能效率提供技术参考。全文采用模块化设计思路,为新能源与储能系统的仿真研究提供了实用案例。

xiaoheshang_123的博客 299

spring boot mybatis 整合_SpringBoot学习笔记二之Spring整合Mybatis

SpringBoot学习笔记二之Spring整合Mybatis在learn-admin-component子工程中加入搭建环境所需要的具体依赖(因为比较长配置信息放到文档后面)在learn-admin-webui配置jdbc.propertis配置内容jdbc.user=rootjdbc.password=jdbc.url=jdbc:mysql://localhost:3306/project_l...

weixin_39723899的博客 84

手把手教你学pcie--用Verilog搭建PCIe控制器核心模块

PCIe控制器是硬件设计的核心模块,负责实现设备与主机之间的高速通信。本文将以Verilog语言为例,分步骤讲解如何从零构建一个简化的PCIe控制器核心模块,涵盖事务层(TLP)生成、数据链路层(DLLP)处理和物理层(PHY)接口适配。目标是为嵌入式开发者、FPGA工程师提供一个可扩展的硬件设计框架。​。

MHD0815的博客 341

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

mybatis笔记<二> 整合spring

mybatis与spring整合需要添加几个jar包,mybatis-spring, spring-context, spring-jdbc 1. spring ioc只要一个jar包就ok 2. 我用了c3p3数据库连接池 跟笔记<一>比,需要修改的地方 pom.xml <?xml version="1.0" encoding="UTF-8"?> <...

weixin_30849591的博客 78

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

spring logback mysql_SpringBoot学习笔记二之Spring整合Mybatis

在learn-admin-component子工程中加入搭建环境所需要的具体依赖(因为比较长配置信息放到文档后面)在learn-admin-webui配置jdbc.propertis配置内容jdbc.user=rootjdbc.password=jdbc.url=jdbc:mysql://localhost:3306/project_learn?useUnicode=true&charac...

weixin_39844481的博客 90

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

Spring学习笔记:Spring整合Mybatis(mybatis-spring.jar)(二:mybatis整合spring)

http://blog.youkuaiyun.com/qq598535550/article/details/51703190 二、Spring整合mybatis其实是在mybatis的基础上实现Spring框架     1、依赖的jar包,maven引入依赖: <dependency> <groupId>junit</groupId...

weixin_33763244的博客 130

Mybatis学习笔记二:代理接口xml文件配置,关联查询,逆向工程,spring整合Mybatis框架

文章目录1. Mybatis学习笔记二:1.1. 序列化和反序列化1.2. ParameterType(输入参数类型)1.2.1. 思考1.3. resultMap手动映射1.4. 动态sql1.4.1. if标签2. 关联查询2.1. 一对多关联2.2. 一对多关联实现2.3. 一对一关联配置2.4. 测试代码3. Mybatis的逆向工程3.1. 逆向工程用途3.2. 逆向工程的使用3.3. ...

公子&小白的博客 416

Spring——Spring整合MyBatis

Spring——Spring整合MyBatis

贝尔摩德苦艾酒 2万+

Spring 整合Mybatis。

▶ Junit运行后是基于Spring环境运行的,所以Spring提供了一个专用的类运行器,这个务必要设置,这个类运行器就在Spring的测试专用包中提供的,导入的坐标就是这个东西`SpringJUnit4ClassRunner`○ SqlSessionFactoryBean是前面我们讲解FactoryBean的一个子类,在该类中将SqlSessionFactory的创建进行了封装,简化对象的创建,我们只需要将其需要的内容设置即可。在运行类中,从IOC容器中获取Service对象,调用方法获取结果。

yzh2776680982的博客 2363

Spring整合MyBatis——超详细

Spring整合MyBatis——超详细一、Spring整合MyBatis的三个关键点二、整合步骤1、创建一个Maven项目2、在pom.xml文件中添加jar包的依赖2、配置MyBatis文件(1) 新建一个实体类的包和User实体类(2) 编写实体类(3) 新建Mapper接口包和UserMapper接口(3) 新建jdbc资源文件 jdbc-config.properties(4) 新建mybatis配置文件 mybatis.xml(5) 新建logj4j的日志配置文件log4j.properties

qq_42662759的博客 4万+

Spring5学习笔记—整合MyBatis

在我们之前的系列文章中,我们已经深入探讨了Spring5IOC和AOP,它们是Spring框架的基石。下面我们接着讨论开始讨论Spring5对于持久层框架MyBatis的整合,让我们一起开启新的的篇章吧。以上便是本文的全部内容,本人才疏学浅,文章有什么错误的地方,欢迎大佬们批评指正!我是Leo,一个在互联网行业的小白,立志成为更好的自己。如果你想了解更多关于Leo,可以关注公众号-程序员Leo,后面文章会首先同步至公众号。

分享思想,留下痕迹。 2万+

Spring和Mybatis的整合

spring和mybatis的整合,回顾之前的笔记

beautifulsen的博客 6022

Spring整合Mybatis

需维护独立的mybatis-config.xml文件:数据源、事务、映射配置分散在不同文件:修改配置需要重启应用。

2302_77465225的博客 1919

Spring:Spring整合Mybatis

对其中分析,看看哪些可以交给spring管理:Mybatis程序核心对象分析从图中可以获取到,真正需要交给Spring管理的是整合Mybatis,就是将Mybatis用到的内容交给Spring管理,分析下配置文件第一行读取外部properties配置文件,Spring有提供具体的解决方案,需要交给Spring第二行起别名包扫描,为SqlSessionFactory服务的,需要交给Spring第三行主要用于做连接池,Spring之前我们已经整合了Druid连接池,这块也需要交给Spring。

qq_41187116的博客 1524
上一篇: spring的bean容器创建的笔记(一)
下一篇: jvm字节码-clinit及本地变量表
riapgypm
博客等级 码龄17年 15粉丝 40原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值