0
点赞
收藏
分享

微信扫一扫

Spring复习—MapperScannerConfigurer

舟海君 2022-03-14 阅读 77

目录

介绍和场景

之前的繁琐配置


 

MapperSacnnerConfigurer是Spring和Mybatis整合的jar包中的一个类

<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>

<!--    mapper扫描-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wyh.product.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

然后我们发现我们dao层不用写实现类了,直接service层注入dao层接口即可;

1、在配完dao接口后,还需要实现它,打开sqlSession,getMapper(); 

package com.huang.dao;

import com.huang.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper {
    //我们的所有操作,都使用sqLSession来执行,在原来,现在都使用sqLSessionTemplate;
    //你会发现sqlSessionTemplate里面具有所有sqlSession的方法(连接数据库..和一些操作)
    private SqlSessionTemplate sqlSession;

    //通过构造的方式注入一个SqlSessionTemplate(这个sqlSessionTemplate是如何的得来的?)
    //是通过sqlSessionFactory得来的
    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    //mybatis的操作全部放在一个类中,而不是像之前那样和获取sqlSession的操作放在一起
    @Override
    public List<User> select() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.select();
    }
}

 2、或者是实现sqlSessionDaoSupport

package com.huang.dao;

import com.huang.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    @Override
    public List<User> select() {
        //SqlSession sqlSession = getSqlSession();
        //UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        //最精简版
        return getSqlSession().getMapper(UserMapper.class).select();
    }
}

MapperSacannerConfigurer可以通过配置包路径来自动扫描包接口从而生成映射器(java对象与sql字段名进行转化),并且为它们创建MapperFactoryBean,那么问题来了


MapperFactoryBean的作用是什么呢?

他可以配置接口文件并且注入SqlSessionFactory,完成一个Bean的实例化,注入sqlSessionFactory后,我们就相当于dao与.xml绑上了

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

作用:实现dao层接口,创建代理类(jdk代理你们都是知道的,一个委托类加一个代理类,这两个类都需要实现接口) ,注入到应用程序中,因为是动态代理,所以是在运行时环境中产生;


配置MapperScannerConfigurer后,他就不需要再指定SqlSessionFactory和SqlSessionTemplate了;他会自动在路径下创建MapperFactoryBean自动装配;

举报

相关推荐

0 条评论