JavaEE MyBatis与Spring的整合——基于mapper接口方式开发(教材学习笔记)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/83784210

在MyBatis与Spring的整合开发中虽然可以通过传统的DAO开发方式,但是采用DAO方式会产生大量的重复代码,因此学习另外一种编程方式就很重要了,即Mapper接口编程(本章代码是基于上一篇博客的点这里

一、基于MapperFactoryBean的整合

MapperFactoryBean是Mapper-Spring团队提供的一个用于根据Mapper接口生成Mapper对象的类,该类在Spring配置文件中可以配置相关参数

1.在src目录下,创建一个com.itheima.mapper包,然后在该包中创建CustomerMapper接口以及对应的映射文件

package com.itheima.mapper;
import com.itheima.po.Customer;
public interface CustomerMapper {
	public Customer findCustomerById(Integer 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">
<mapper namespace="com.itheima.mapper.CustomerMapper">
    <select id="findCustomerById" parameterType="Integer" resultType="Customer">
        select * from t_customer where id=#{id}
    </select>
</mapper>

2.MyBatis的配置文件中,引入新的映射文件

<mapper resource="com/itheima/mapper/CustomerMapper.xml"/>

3.在Spring的配置文件中创建一个id为customerMapper的Bean,代码如下:

<bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
         <property name="mapperInterface" value="com.itheima.mapper.CustomerMapper"/>
         <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

以上代码为MapperFactoryBean指定了接口及SqlSessionFactory

4.在测试类中编写测试方法findCustomerByIdMapperTest()

@Test
	public void findCustomerByIdMapperTest() {
		ApplicationContext act= new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerMapper customerMapper = act.getBean(CustomerMapper.class);
		Customer customer = customerMapper.findCustomerById(1);
		System.out.println(customer);
	}

5.运行测试结果如下:

二、基于MapperScannerConfigurer的整合

在实际的项目中,DAO层会包含很多接口如果每个接口都像前面那样在Spring配置文件中配置,那么不但会增加工作量也会使Spring配置文件非常臃肿,为此MyBatis—Spring团队提供了一种可以自动扫描的形式配置MyBatis中的映射器—采用MapperScannerConfigurer类

1.使用MapperScannerConfigurer非常简单,只需要在Spring的配置文件中编写如下代码:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.mapper"/>
    </bean>

2.将上边第二步和第三步的代码注释掉,再次运行测试方法,结果如下:

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/83784210