Layman Mybatis (a): mapper

Disclaimer: This article is Xu Chen original article, shall not be reproduced without my permission. https://blog.csdn.net/Mrxuchen/article/details/82798115

Mapper is Mybatis most complex and the most important component, it has an interface plus xml file (or notes) composition, parameters can be configured in a mapper, all kinds of complex SQL statements, stored procedures, cache, cascading content, and mapped to the specified pojo or other objects by a simple mapping rule, JDBC mapper can effectively eliminate the underlying code.

In Mybatis application development, development of mapping accounted for 80% of the total workload. In the top-level element to configure MyBatis mapper is not much, but inside some of the details, such as caching, cascade, # and $ characters replaced, parameters, stored procedures, mapping rules we need further study.

Currently Mybatis mapper in two ways:

  • xml mapper
    xml mapper MyBatis is native support for the way, very powerful.
  • Interface Mapper

Defined xml mapper

xml mapper supports writing SQL statements in the file xml format.

<?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>

Configuration xml mapper

For MyBatis is used independently or integrate the two different scenarios and the Spring Framework, you may be used two kinds of alternative ways register xml mapper.

Independently MyBatis
register mapper xml configuration file only when MyBatis independently: achieved by the mapper node (e.g. mybatis-config.xml).

<configuration>
    <mappers>
        <!-- 注册xml映射器: 2种方式 -->
        <!-- 方式一: 使用相对于类路径的资源引用 -->
        <mapper resource="org/chench/test/mybatis/mapper/xml/TestMapper.xml"/>

        <!-- 方式二: 使用完全限定资源定位符(URL) -->
        <!--<mapper url="file:///var/config/TestMapper.xml" />-->
    </mappers>
</configuration>

MyBatis integrated in the Spring Framework
Spring Framework when integrated MyBatis, register xml mapper There are two alternative ways: either in MyBatis configuration file (eg: mybatis-config.xml) configuration, or directly in the SqlSessionFactoryBean register through the property mapperLocations.
(1) registered on the MyBatis mapper xml configuration file (eg: mybatis-config.xml), but this time must be specified by the position profile attributes MyBatis configLocation in the SqlSessionFactoryBean.

<!-- 配置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>

Use xml mapper

For use xml mapper, if the call SqlSession used independently or integrated substantially uniform in the Spring Framework. Note: when using MyBatis integrates the Spring framework, no need to obtain sqlSession objects directly from sqlSessionFactory, but rather can be used sqlSession objects spring management. In addition, when the Spring framework MyBatis integrated, you may also be used directly via xml mapper interface.

MyBatis used independently
when used independently MyBatis, xml mapping can only be used for SqlSession call.

// 从类路径下的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();

Integrated in the Spring Framework MyBatis
different (1) using the mapper xml SqlSession call, basically the same manner as when independently MyBatis, acquired SqlSession way of example only.

// 启动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);

At this time, we need to be injected in the Spring Framework SqlSession instance.

** use interface calls xml mapper **

When integrated MyBatis the Spring framework, using xml mapper called by the addition SqlSession example, it can also be called directly by the interface. Note: At this point in time is defined Java interfaces and registered xml mapping needs to follow certain conventions.
First, the interface must be defined in the Java org.mybatis.spring.mapper.MapperScannerConfigurer basePackage attribute specified packets or sub-packets, as follows:

org.mybatis.spring.mapper.MapperScannerConfigurer registered by the Spring Framework, and the attribute value set basePackage org.chench.test.mybatis.mapper.impl, then the corresponding Java interface can only be defined in the Java package org.chench.test. under mybatis.mapper.impl, Bean and registered by the Spring framework, as follows:

Interface package location where // Jav
Package org.chench.test.mybatis.mapper.impl;
// the interface register by the Spring Framework Bean
@Repository
public interface DemoMapper {
; public between selectOne Demo (Long ID)
}
Next, when the registration mapper xml namespace attribute needs to be set to the full class name of the Java interface, while the setting operation for the sentence elements id attribute specifies the name of the interface method.

<?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>

After the registration of the agreement to comply with the corresponding xml mapper, it can directly interface calls xml mapper through the corresponding Java.

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

xml mapping method uses comparison
xml use according MyBatis mapper different usage scenario, summarized as follows:
(1) When used independently MyBatis, only by using the SqlSession xml mapping, must be specified when calling the mapper xml operating statement id, more complicated.

Test = sqlSession.selectOne the Test ( "org.chench.test.mybatis.mapper.selectOneTest",. 1);
(2) when integrated in the Spring Framework MyBatis, more flexible use xml mapper. In addition to use by SqlSession, also it can be called directly from Java interface. For developers, the direct call interface methods will be more concise; while using a flexible and powerful xml mapper, has multiple purposes.

Guess you like

Origin blog.csdn.net/Mrxuchen/article/details/82798115