• mybatis spring代理开发


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

      

    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>

    使用上面代码测试即可

  • 相关阅读:
    一个网站架构的变迁
    网络编程
    http协议篇
    第1篇 编程能力是什么
    django中的cookies和session机制
    django的认证与授权系统
    python的异常处理
    第0篇
    mysql优化和全局管理杂记
    k8s中pod的资源配置详解
  • 原文地址:https://www.cnblogs.com/WarBlog/p/14955498.html
Copyright © 2020-2023  润新知