mybatis mapper代理开发

1、在上一章dao开发基础上增加mapper.xml和mapper.java

  mybatis mapper代理开发

 

2、修改mybatis核心配置文件,包扫描  

    <mappers>
        <!-- <mapper resource="mybatis/User.xml"/> -->
        <package name="com.xxx.mybatis.spring.mapper"/>
    </mappers>

3、通过MapperFactoryBean创建代理对象

    <!-- 通过MapperFactoryBean创建代理对象 -->
    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.xxx.mybatis.spring.mapper.UserMapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

4、测试

    ApplicationContext applicationContext;

    @BeforeEach
    void setUp() throws Exception {
    applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }

    /**
     * Test method for {@link com.xxx.mybatis.spring.mapper.UserMapper#findUserById(int)}.
     */
    @Test
    void testFindUserById() {
    UserMapper mapper= (UserMapper) applicationContext.getBean("userMapper");
    User user=mapper.findUserById(1);
    System.out.println(user);
    }

此方法问题:需要针对每个mapper进行配置,麻烦。

 5、通过MapperScannerConfigurer进行mapper扫描

    <!-- 通过MapperScannerConfigurer进行mapper扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 
        指定扫描的包名
        扫描多个包,使用半角逗号隔开
         -->
        <property name="basePackage" value="com.xxx.mybatis.spring.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

使用上面代码测试即可

 

上一篇:Spring深入浅出(一),HelloWorld程序


下一篇:spring源码学习-1