MyBatis与Spring整合细节的优化
  TEZNKK3IfmPf 2023年11月15日 32 0

MyBatis与Spring整合细节的优化  整合过程参考
优化部分: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);
    }
}


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月17日   48   0   0 dremiosqltable
  TEZNKK3IfmPf   2024年05月17日   46   0   0 JSpspring
  TEZNKK3IfmPf   2024年05月17日   52   0   0 sqlmysql
  TEZNKK3IfmPf   2024年05月17日   38   0   0 sqlcube
TEZNKK3IfmPf