之间简单配置过SqlSessionFactory,但这并不是正规的整合方式,MyBatis提供了mybatis-spring.jar专门用于两大框架的整合
Spring整合Mybatis的步骤:
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-jdbcartifactId>
- <version>5.2.5.RELEASEversion>
- dependency>
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatis-springartifactId>
- <version>2.0.4version>
- dependency>
编写Mapper和Mapper.xml
配置SqlSessionFactory和MapperScannerConfigurer
- <bean class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource">property>
- bean>
-
- <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
users = userMapper.SelectAll(); - for (User user : users) {
- System.out.println(user);
- }
- }
-
-
-
-
-
- public interface UserMapper {
- List
SelectAll(); - }
整合包里提供了一个SqlSessionFactoryBean和一个扫描Mapper的配置对象,SqlSessionFactoryBean一旦实例化,就开始扫描Mapper并通过动态代理产生Mapper的实现类,存储到Spring容器中,相关类:
SqlSessionFactory:需要进行配置,用于提供SqlSessionFactory
MapperSacnnerConfigurer:需要进行配置,用于扫描指定mapper注册BeanDefinition
MapperFactoryBean:Mapper的FactoryBean,获得指定Mapper时调用getObject方法
ClassPathMapperScanner:definition.setAutowireMode(2)修改了自动注入状态,所以MapperFactoryBean中setSqlSessionFactory会自动注入进去