MyBatis与Spring整合细节的优化

来源:互联网 发布:宿州影楼美工招聘兼职 编辑:程序博客网 时间:2024/06/08 07:29

MyBatis与Spring整合细节的优化
整合过程参考:http://blog.csdn.net/leisure_life/article/details/72778179
优化部分:spring中配置接口扫描

 <!-- mapper的配置            name:根据接口生成代理对象        <bean id="userMaper" class="org.mybatis.spring.mapper.MapperFactoryBean">            <property name="mapperInterface" value="com.hl.ld.mapper.UserMapper"/>            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>        </bean>         -->        <!-- 一个一个接口配置太繁琐了,自动扫描mapper接口             也需要遵循mapper开发规范            sqlSessionFactoryBeanName        -->        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">            <!-- 指定扫描的包名                 扫描多个包用半角逗号隔开                获取mapper时是mapper接口名的首字母小写            -->            <property name="basePackage" value="com.hl.ld.mapper"/>            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>        </bean>

测试:优化部分,接口的id为接口名首字母小写

package com.hl.ld.test;import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.hl.ld.mapper.UserMapper;import com.hl.ld.pojo.User;public class SpringMybatisTest {    private ApplicationContext applicationContext;    @Before    public void before(){        String configLocation = "classpath:spring/applicationContext.xml";        //获取spring容器        applicationContext = new ClassPathXmlApplicationContext(configLocation);    }    @Test    public void testFindUserById() throws Exception{        UserMapper userMaper = (UserMapper) applicationContext.getBean("userMapper");        User user = userMaper.findUserById(3);        System.out.println(user);    }}
原创粉丝点击