zoukankan      html  css  js  c++  java
  • 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>

    使用上面代码测试即可

  • 相关阅读:
    【Lua】LuaForWindows_v5.1.4-46安装失败解决方案
    【C++】指针引发的bug
    【C++】指针引发的bug
    【C++】位操作(3)-获取某位的值
    bzoj1444
    bzoj1758
    bzoj3091
    poj1741 bzoj2152
    bzoj2125 3047
    bzoj3669
  • 原文地址:https://www.cnblogs.com/WarBlog/p/14955498.html
Copyright © 2011-2022 走看看