zoukankan      html  css  js  c++  java
  • spring和mybatis的整合开发(基于MapperScannerConfigurer的整合开发(适用于复杂项目,接口较多的情况))

    在实际项目中,Dao层会包含很多接口,这样会导致spring配置文件过于臃肿。这时就需要采用扫描包的形式来配置mybaits中的映射器。

    采用MapperScannerConfigurer来实现。

    MapperScannerConfigurer类在spring配置文件中可以配置以下几个属性:

    1.basePackage:用于指定映射接口文件的包路径,当需要扫描多个包时使用逗号或分号隔开。

    2.annotationClass:指定了要扫描的注解名称,只有被注解标示的类才会被配置为映射器。

    3.markerInterface:指定创建映射器的接口。

    4.sqlSessionFactoryBeanName:指定在spring中定义的sqlSessionFactory的bean名称。

    5.sqlSessionTemplateBeanName:指定在spring中定义的sqlSessionTemplate的bean名称。如果定义此属性,那么sqlSessionFactoryBeanName将不起作用。

    例如:

    CustomerMapper 接口,用@Repository表示此接口是一个dao层。
    @Repository//标示是一个dao层
    public interface CustomerMapper {
    public Customer findCustomerById(Integer id);
    }

    mapper映射文件
    <mapper namespace="com.itheima.po.mapper.CustomerMapper">
    <select id="findCustomerById" parameterType="Integer" resultType="customer">
    select * from t_customer where id=#{id}
    </select>
    </mapper>
    在spring的配置文件中配置
    <!--基于MapperScannerConfigurer的开发-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.itheima.po.mapper"/>//用于扫描映射文件包,可以将映射文件放入不同的包中。
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>//value值是配置=mybatis工厂时的id值sqlSessionFactory
    <property name="annotationClass" value="org.springframework.stereotype.Repository"/>//根据注解进行扫描,成mapper对象。
    </bean>
    最后测试,成功。
  • 相关阅读:
    Docker 安装及使用
    明明白白学 同步、异步、阻塞与非阻塞
    ArrayList 并发操作 ConcurrentModificationException 异常
    shell 脚本防止ddos
    shell 脚本备份数据库
    shell 脚本猜数字
    shell 脚本检测主从状态
    tomcat 结合apache 动静分离
    shell 脚本检测网站存活
    zabbix 4.0 版本 yum安装
  • 原文地址:https://www.cnblogs.com/jasonboren/p/10598083.html
Copyright © 2011-2022 走看看