zoukankan      html  css  js  c++  java
  • 深入浅出mybatis之映射器

    目录

    概述

    映射器是MyBatis中最核心的组件之一,在MyBatis 3之前,只支持xml映射器,即:所有的SQL语句都必须在xml文件中配置。而从MyBatis 3开始,还支持接口映射器,这种映射器方式允许以Java代码的方式注解定义SQL语句,非常简洁。

    XML映射器

    xml映射器是MyBatis原生支持的方式,功能非常强大。

    定义xml映射器

    xml映射器支持将SQL语句编写在xml格式的文件中。

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="org.chench.test.mybatis.mapper">
    	<select id="selectOneTest" resultType="org.chench.test.mybatis.model.Test">
    		select * from test where id = #{id}
    	</select>
    </mapper>
    

    配置xml映射器

    对于MyBatis是独立使用还是与Spring框架集成这2种不同的场景,可以使用2种可选的方式注册xml映射器。

    • 独立使用MyBatis

    独立使用时注册xml映射器只能在MyBatis配置文件中(如:mybatis-config.xml)通过mapper节点实现。

    <configuration>
        <mappers>
            <!-- 注册xml映射器: 2种方式 -->
            <!-- 方式一: 使用相对于类路径的资源引用 -->
            <mapper resource="org/chench/test/mybatis/mapper/xml/TestMapper.xml"/>
    
            <!-- 方式二: 使用完全限定资源定位符(URL) -->
            <!--<mapper url="file:///var/config/TestMapper.xml" />-->
        </mappers>
    </configuration>
    
    • 在Spring框架中集成MyBatis

    在Spring框架中集成MyBatis时,注册xml映射器有2种可选的方式:既可以在MyBatis配置文件中(如:mybatis-config.xml)配置,也可以直接在SqlSessionFactoryBean中通过属性mapperLocations进行注册。
    (1)将xml映射器注册放在MyBatis配置文件中(如:mybatis-config.xml),但是此时必须在SqlSessionFactoryBean中通过属性configLocation指定MyBatis配置文件的位置。

    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource"/>
    	<!-- 指定MyBatis配置文件(只支持类路径,典型的值为"WEB-INF/mybatis-configuration.xml") -->
    	<property name="configLocation" value="mybatis-config.xml"/>
    </bean>
    

    (2)在SqlSessionFactoryBean中通过属性mapperLocations进行注册xml映射器。

    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource"/>
    	<!-- 注册xml映射器 -->
    	<property name="mapperLocations" value="classpath*:org/chench/test/mybatis/mapper/xml/**/*.xml"/>
    </bean>
    

    使用xml映射器

    对于xml映射器的使用方式,如果使用SqlSession进行调用,独立使用或者在Spring框架中集成基本上是一致的。需要注意的是:当MyBatis在Spring框架中集成使用时,不需要直接从sqlSessionFactory中获取sqlSession对象,而是可以使用spring管理的sqlSession对象。另外当在Spring框架中集成MyBatis时,还可以直接通过接口使用xml映射器。

    • 独立使用MyBatis

    独立使用MyBatis时,对于xml映射器只能使用SqlSession进行调用。

    // 从类路径下的xml配置中构建SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream is = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    // 从sqlSessionFactory中获取sqlSession
    // SqlSession的作用域最好是请求或方法域,且在使用完毕之后及时释放资源,而且一定要确保资源得到释放
    SqlSession sqlSession =	sqlSessionFactory.openSession();
    // 从xml映射配置中查询
    Test test =	sqlSession.selectOne("org.chench.test.mybatis.mapper.selectOneTest", 1);
    sqlSession.close();
    
    • 在Spring框架中集成MyBatis

    (1)使用SqlSession调用xml映射器,方式与独立使用MyBatis时基本一致,只是获取SqlSession实例的方式不同。

    // 启动spring容器
    ApplicationContext context = new ClassPathXmlApplicationContext("mybatis-spring.xml");
    // 使用xml映射器
    // 不需要直接从sqlSessionFactory中获取sqlSession对象,而是可以使用spring管理的sqlSession对象
    //	SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) context.getBean("sqlSessionFactory");
    //	SqlSession sqlSession =	sqlSessionFactory.openSession();
    //	Test test =	sqlSession.selectOne("org.chench.test.mybatis.mapper.selectOneTest", 1);
    
    // 直接使用spring提供的sqlSession
    SqlSession sqlSession = (SqlSession) context.getBean("sqlSession");
    Test test =	sqlSession.selectOne("org.chench.test.mybatis.mapper.selectOneTest", 1);
    

    此时,需要在Spring框架中注入SqlSession实例。

    <!-- 在Spring框架中注入SqlSession实例-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    	<constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    

    (2)使用接口调用xml映射器
    当在Spring框架中集成MyBatis时,对于xml映射器的使用除了可以通过SqlSession实例进行调用,还可以直接通过接口进行调用。注意:此时在定义Java接口和注册xml映射器时需要遵循一定的约定。
    首先,定义的Java接口必须在org.mybatis.spring.mapper.MapperScannerConfigurer的属性basePackage指定的包或者子包下,如下所示:

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<property name="basePackage" value="org.chench.test.mybatis.mapper.impl"/>
    </bean>
    

    org.mybatis.spring.mapper.MapperScannerConfigurer由Spring框架注册,并设置basePackage属性值为org.chench.test.mybatis.mapper.impl,那么对应的Java接口就只能定义在Java包org.chench.test.mybatis.mapper.impl下,并通过Spring框架注册Bean,如下所示:

    // Jav接口所在包位置
    package org.chench.test.mybatis.mapper.impl;
    // 接口通过Spring框架注册Bean
    @Repository
    public interface DemoMapper {
        public Demo selectOne(long id);
    }
    

    其次,注册xml映射器时需要将namespace属性设置为上述Java接口的完整类名称,同时设置操作语句元素的id属性为接口内的指定方法名称。

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!-- 将xml映射器的namespace属性设置为完整的接口类名称 -->
    <mapper namespace="org.chench.test.mybatis.mapper.impl.DemoMapper">
    	<!-- 将操作语句元素的id属性设置为接口方法名称 -->
    	<select id="selectOne" resultType="org.chench.test.mybatis.model.Demo">
            SELECT * FROM demo WHERE id=#{id}
        </select>
    </mapper>
    

    在遵守上述约定注册对应的xml映射器之后,就可以直接通过对应的Java接口调用xml映射器了。

    // 启动spring容器
    ApplicationContext context = new ClassPathXmlApplicationContext("mybatis-spring.xml");
    // 使用接口调用xml映射器
    DemoMapper demoMapper = context.getBean(DemoMapper.class);
    Demo demo = demoMapper.selectOne(1);
    
    • xml映射器使用方法的比较

    xml映射器的使用方式根据MyBatis的使用场景而不同,总结如下:
    (1)独立使用MyBatis时,只能通过SqlSession使用xml映射器,调用时必须指定xml映射器中的操作语句id,比较繁琐。

    Test test =	sqlSession.selectOne("org.chench.test.mybatis.mapper.selectOneTest", 1);
    

    (2)在Spring框架中集成MyBatis时,使用xml映射器比较灵活。除了可以通过SqlSession使用,还可以通过Java接口直接调用。对于开发者来说,直接调用接口方法会更加简洁;同时还能使用xml映射器的灵活与强大功能,可谓一举多得。

    接口映射器

    接口映射器是从MyBatis 3才开始支持的,其实就是支持在Java接口方法上通过注解方式编写SQL语句,而不再需要xml文件格式的配置。但请注意:使用注解编写SQL语句这种方式在某些场景下存在一定的限制,特别是处理复杂SQL的时候。虽然其有一定的简洁性,但同时也带来了局限性。通常都是将xml映射器和接口映射器联合使用。

    定义接口映射器

    定义接口映射器就是通过注解在Java接口方法上编写SQL语句,如下所示:

    // 定义接口映射器
    public interface TestMapper {
    	// 通过MyBatis的注解在Java接口方法上编写SQL语句
    	@Select("select * from test where id = #{id}")
    	Test selectOneTest(long id);
    }
    

    配置接口映射器

    对于MyBatis是独立使用还是与Spring框架集成这2种不同的场景,注册接口映射器的方式各不相同,必须注意这一点。

    • 独立使用MyBatis

    在独立使用MyBatis时,接口映射器只能在MyBatis的配置文件中(如:mybatis-config.xml)通过mapper节点指定,如:

    <mappers>
    	<!-- 注册接口映射器: 2种方式 -->
    	<!-- 方式一: 明确注册每一个接口 -->
    	<!--
    	<mapper class="org.chench.test.mybatis.mapper.impl.TestMapper" />
    	<mapper class="org.chench.test.mybatis.mapper.impl.StudentMapper" />
    	-->
    	<!-- 方式二: 指定映射器接口所在Java包名称,则该包下的所有映射器接口都会被注册 -->
    	<package name="org.chench.test.mybatis.mapper.impl"/>
    </mappers>
    
    • 在Spring框架中集成MyBatis

    在Spring框架中集成MyBatis时,接口映射器只能通过org.mybatis.spring.mapper.MapperScannerConfigurer注册,指定其basePackage属性值为需要注册映射器接口所在的包,可以在该包及其子包下定义接口映射器。

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<!-- 定义接口映射器所在的Java包 -->
    	<property name="basePackage" value="org.chench.test.mybatis.mapper.impl"/>
    </bean>
    

    使用接口映射器

    根据MyBatis的使用场景不同,使用接口映射器的方式也不同。

    • 独立使用MyBatis

    独立使用MyBatis时,只能通过SqlSession使用接口映射器,此时也需要开发者自己释放SqlSession资源。

    // 从类路径下的xml配置中构建SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream is = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    // 从sqlSessionFactory中获取sqlSession
    // SqlSession的作用域最好是请求或方法域,且在使用完毕之后及时释放资源,而且一定要确保资源得到释放
    SqlSession sqlSession =	sqlSessionFactory.openSession();
    // 从映射器接口中查询
    Test test = sqlSession.getMapper(TestMapper.class).selectOneTest(1);
    sqlSession.close();
    
    • 在Spring框架中集成MyBatis

    在Spring框架中集成MyBatis时,接口映射器的Bean由Spring框架来管理,此时只需要直接获取对应的接口映射器Bean并调用方法即可。

    // 启动spring容器
    ApplicationContext context = new ClassPathXmlApplicationContext("mybatis-spring.xml");
    // 从Spring容器中获取接口映射器Bean
    TestMapper testMapper =	context.getBean(TestMapper.class);
    Test test =	testMapper.selectOneTest(1);
    

    总结与对比

    1. 从MyBatis 3开始,同时支持2种类型的映射器:xml映射器和接口映射器。
    2. xml映射器是MyBatis原生支持的映射器方式,优点是功能强大,缺点是配置显得臃肿和复杂;接口映射器支持通过注解的方式在Java接口方法上编写SQL语句,优点是简洁,不再依赖外部xml配置,缺点是功能没有xml映射器强大。需要特别注意的是,在接口映射器中使用@SelectProvider注解动态拼装SQL时存在SQL注入攻击的风险。因此,通常都是将二者联合使用,即可以使用接口映射器带来的简洁性,也能使用xml映射器的强大功能。
    3. 2种映射器都可以分为独立使用和在Spring框架中集成使用2种不同的方式,独立使用时需要开发者自己处理事务管理和资源释放;在Spring框架中集成时事务管理和资源释放交给Spring框架处理,对开发者是透明的,更加高效和友好。
    4. 对于批量添加记录需要返回主键字段值的需求,只能在xml映射器中实现,接口映射器无能为力。
  • 相关阅读:
    linux查看硬件信息及驱动设备相关整理
    qt 画图相关
    glaux.h vs2008
    技巧:Vimdiff 使用
    Linux下显示硬件信息(二)lshw
    Linux下硬件信息查看(一)dmidecode
    qt delegate
    RFKill 【解决opensuse11.4 无法开启无线网的问题】
    板子上运行提示 找不到qml插件
    CRISPDM
  • 原文地址:https://www.cnblogs.com/nuccch/p/9056482.html
Copyright © 2011-2022 走看看