Spring整合Mybatis

之间简单配置过SqlSessionFactory,但这并不是正规的整合方式,MyBatis提供了mybatis-spring.jar专门用于两大框架的整合

 Spring整合Mybatis的步骤:

  • 导入MyBatis整合Spring的相关坐标
 
      org.springframework
      spring-jdbc
      5.2.5.RELEASE
    
    
      org.mybatis
      mybatis-spring
      2.0.4
    
  • 编写Mapper和Mapper.xml

  • 配置SqlSessionFactory和MapperScannerConfigurer

    
        
    


    

        

    
    
        
        
        
        
    


  
       
    
  •  编写测试代码
    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();
}

 

Spring整合MyBatis的原理剖析

整合包里提供了一个SqlSessionFactoryBean和一个扫描Mapper的配置对象,SqlSessionFactoryBean一旦实例化,就开始扫描Mapper并通过动态代理产生Mapper的实现类,存储到Spring容器中,相关类:

  • SqlSessionFactory:需要进行配置,用于提供SqlSessionFactory

  • MapperSacnnerConfigurer:需要进行配置,用于扫描指定mapper注册BeanDefinition

  • MapperFactoryBean:Mapper的FactoryBean,获得指定Mapper时调用getObject方法

  • ClassPathMapperScanner:definition.setAutowireMode(2)修改了自动注入状态,所以MapperFactoryBean中setSqlSessionFactory会自动注入进去

你可能感兴趣的:(spring,mybatis,java)