Mapper代理模式开发Dao

本文介绍如何在MyBatis中配置Mapper接口,包括使用MapperFactoryBean进行单个接口配置的方法及通过MapperScannerConfigurer进行包扫描配置的方式,并提供了一个简单的测试案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.配置Mapper

a.单个接口配置MapperFactoryBean:

<!-- 动态代理Dao开发,第一种方式 -MapperFactoryBean -->

  <bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" abstract="true" lazy-init="true">

     <property name="sqlSessionFactory" ref="sqlSessionFactory" />

    </bean>

    <!-- 用户动态代理扫描 -->

    <bean parent="baseMapper">

      <property name="mapperInterface" value="com.itheima.mybatis.mapper.UserMapper" />

   </bean>

b.配置包扫描器(推荐使用):

<!-- 动态代理Dao开发,第一种方式,包扫描器(推荐使用) -->

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

         <!-- basePackage:配置映射包装扫描,多个包时用","";"分隔 ,有了该包扫描器就可以加载出该包下所有的mapper-->

<property name="basePackage" value="com.itheima.mybatis.mapper" />

   </bean>

2.测试

public class UserMapperTest {

   

    private ApplicationContext applicationContext;

   

    @Before

    public void init(){

       applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    }

 

    @Test

    public void testGetUserById() {

       UserMapper userMapper = applicationContext.getBean(UserMapper.class);

       User user = userMapper.getUserById(10);

       System.out.println(user);

 

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值