zoukankan      html  css  js  c++  java
  • spring和mybatis的整合开发(基于MapperFactoryBean的整合开发(方便简单不复杂))

    MapperFactoryBean是mybati-spring团队提供的一个用于根据mapper接口生成mapper对象的类。

    在spring配置文件中可以配置以下参数:

    1.mapperInterface:用于指定接口

    2.sqlSessionFactory:用于指定SqlSessionFactory。

    3.sqlSessionTemplate:用于指定SqlSessionTemplate。如果和sqlSessionFactory同时配置,则只会启用sqlSessionTemplate。

    例如:

    /*
    * 客户持久化类
    */

    public class Customer {
    private Integer id;
    private String username;
    private String jobs;
    private String phone;
        setter/getter
        toString()
    }
    CustomerMapper接口
    public interface CustomerMapper {
    public Customer findCustomerById(Integer id);
    }
    映射文件:namespace命名空间有包名加接口名
    <mapper namespace="com.itheima.po.mapper.CustomerMapper">
    <select id="findCustomerById" parameterType="Integer" resultType="customer">
    select * from t_customer where id=#{id}
    </select>
    </mapper>
    在applicationContext.xml中的配置
    <!--基于MapperFactoryBean开发-->
    <bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.itheima.po.mapper.CustomerMapper"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
    在mybatis-config.xml中的配置
    <!--引入mapper文件位置-->
    <mappers>
    <mapper resource="com/itheima/po/mapper/CustomerMapper.xml"/>
    </mappers>
    测试
    public class FindCustomerByIdTest {
    @Test
    public void findCustomerById() {
    ApplicationContext applicationContex = new ClassPathXmlApplicationContext("applicationContext.xml");
    CustomerMapper customerMapper = applicationContex.getBean(CustomerMapper.class);
    Customer customer = customerMapper.findCustomerById(1);
    System.out.println(customer);
    }
    }
    结果:
    Customer{id=1, username='jason', jobs='java', phone='123456'}
    使用基于mapperFactoryBean来使mybatis和spring的整合开发与传统的Dao方式开发相比,比较简单,没有重复代码,出错也更容易发现。

    使用mapper接口编程需要遵守以下编程规范:
    mapper接口编程方式只需要编写一个接口,然后由mybatis框架根据接口的定义创建接口的动态代理对象。
    1.mapper的接口名称和对应的mapper.xml映射文件的名称必须一致。
    2.mapper.xml文件中的namespace与mapper接口的类路径相同(也就是接口文件和映射文件需要放在一个包中)。
    3.mapper接口中的方法名和mapper.xml中定义的每个执行语句的id相同。
    4.mapper接口中方法的输入参数类型要和mapper.xml中定义的每个sql的parameterType的类型相同。
    5.mapper接口方法的输出参数类型要和mapper.xml中定义的每个sql的resultType的类型相同。

    使用mapper接口开发虽然简单,但是有个问题就是,当接口过多,会导致映射文件也过多,这样配置文件就会显得比较杂乱和臃肿。
    这就要采用另外一种方式整合。基于MapperScannerConfigurer的整合可以解决这个问题。
  • 相关阅读:
    手把手实战:eclipse 搭建 SpringMvc 框架环境
    解决eclipse中Tomcat服务器的server location选项不能修改的问题
    如何解决JSP页面顶端报错 The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
    第二课 --- git的(管理修改和撤销修改、删除文件)
    第二课 ---git时光穿梭(版本回退)
    第一课——git的简介和基本使用
    001——使用composer安装ThinkPHP5
    微信小程序中对于变量的定义
    微信小程序onLaunch修改globalData的值
    7——ThinkPhp中的响应和重定向:
  • 原文地址:https://www.cnblogs.com/jasonboren/p/10597973.html
Copyright © 2011-2022 走看看