0
点赞
收藏
分享

微信扫一扫

MyBatis与Spring整合细节的优化

栖桐 2022-06-24 阅读 72

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);
}
}


举报

相关推荐

0 条评论