Mybatis与Spring整合(二)

Mybatis与Spring整合(二)

MapperScannerConfiger的整合

这篇博文是基于上一篇博客MyBatis与Spring整合继续进行的,前期配置可参考该博客

在src目录下创建com.mapper包,编写CustomerMapper接口以及对应的配置文件,编辑后如下所示

创建CustomerMapper.java,编写根据ID查找信息的方法
package com.mapper;
import com.po.Customer;
public interface CustomerMapper {
    public Customer findCustomerById(Integer id);
}
编写CustomerMapper.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="com.mapper.CustomerMapper">
    <!--根据id查询客户信息 -->
    <select id="findCustomerById" parameterType="Integer"
            resultType="customer">
		select * from t_customer where id = #{id}
	</select>
    <!--添加客户信息 -->
    <insert id="addCustomer" parameterType="customer">
	    insert into t_customer(username,jobs,phone)
	    values(#{username},#{jobs},#{phone})
	</insert>
</mapper>

基于MapperScannerConfigure的整合

MapperScannerConfigure的使用很简单,只需在spring的配置文件applicationContext.xml中添加如下代码

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

其中basePackage是制定映射接口所在包的路径,指定包路径后,会扫描该包及其子包中的所有文件

整合测试

在测试类DaoTest中编写测试方法findCustomerByIdMapperTest()方法,如下

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

运行结果如下
运行结果如下所示

写在最后

MapperScannerConfigure在使用时只需通过basePackage属性制定需要扫描的包,Spring会自动的通过包中的接口来生成映射器,从而提高开发效率。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值