之间简单配置过SqlSessionFactory,但这并不是正规的整合方式,MyBatis提供了mybatis-spring.jar专门用于两大框架的整合
Spring整合Mybatis的步骤:
- 导入MyBatis整合Spring的相关坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
-
编写Mapper和Mapper.xml
-
配置SqlSessionFactory和MapperScannerConfigurer
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 作用:扫描指定的包,产生Mapper对象存储到Spring容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描的包 -->
<property name="basePackage" value="com.xfy.mapper"></property>
</bean>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///book?useSSL=false&useServerPrepStmts=true"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
<bean id="userService" class="com.xfy.service.impl.UserServiceImpl">
<property name="userMapper" ref="userMapper"></property>
</bean>
- 编写测试代码
public static void main(String[] args) throws ParseException, IOException {
ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserService userService = applicationContext.getBean("userService", UserService.class);
userService.show();
UserMapper userMapper = applicationContext.getBean("userMapper", UserMapper.class);
for (User user : userMapper.SelectAll()) {
System.out.println(user);
}
}
public class UserServiceImpl implements UserService, BeanNameAware {
private UserDao userDao;
private UserMapper userMapper;
String Name;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public void show() {
List<User> users = userMapper.SelectAll();
for (User user : users) {
System.out.println(user);
}
}
public interface UserMapper {
List<User> SelectAll();
}
Spring整合MyBatis的原理剖析
整合包里提供了一个SqlSessionFactoryBean和一个扫描Mapper的配置对象,SqlSessionFactoryBean一旦实例化,就开始扫描Mapper并通过动态代理产生Mapper的实现类,存储到Spring容器中,相关类:
SqlSessionFactory:需要进行配置,用于提供SqlSessionFactory
MapperSacnnerConfigurer:需要进行配置,用于扫描指定mapper注册BeanDefinition
MapperFactoryBean:Mapper的FactoryBean,获得指定Mapper时调用getObject方法
ClassPathMapperScanner:definition.setAutowireMode(2)修改了自动注入状态,所以MapperFactoryBean中setSqlSessionFactory会自动注入进去