Mybatis 学习笔记之 与 Spring 整合(八)

一、mabatis 和 spring 整合环境

      Mybatis 学习笔记之 与 Spring 整合(八)

 

二、原始 dao 开发

1.user pojo 类:略。看官想下载源代码的,详见页尾。

2.UserMapper.xml:

Mybatis 学习笔记之 与 Spring 整合(八)

 

3.UserDao.java:

Mybatis 学习笔记之 与 Spring 整合(八)

 

4.UserDaoImp.java:

Mybatis 学习笔记之 与 Spring 整合(八)

 

5.sqlMapConfig.xml:

Mybatis 学习笔记之 与 Spring 整合(八)

 

6.applicationContext.xml:

Mybatis 学习笔记之 与 Spring 整合(八)

 

7.测试类:UserDaoImpTest

Mybatis 学习笔记之 与 Spring 整合(八)

8.结果:

Mybatis 学习笔记之 与 Spring 整合(八)

 

三、mapper 代理开发

1. 通过 MapperFactoryBean 创建代理对象

mapper.java 和 mapper.xml:

Mybatis 学习笔记之 与 Spring 整合(八)

 

其他的不变,但是 applicationContext.xml 文件中 id="userDao" 的 bean 替换成 :

Mybatis 学习笔记之 与 Spring 整合(八)

 

在测试类 UserMapperTest 中:

Mybatis 学习笔记之 与 Spring 整合(八)

此种方法的缺陷需要针对每个mapper进行配置,麻烦。

 

2. 通过 MapperScannerConfigurer 对 mapper 扫描

与第一种代理开发的区别:

Mybatis 学习笔记之 与 Spring 整合(八)

其他的一样。

mapper 批量扫描,从 mapper 包中扫描 mapper 接口,自动创建代理对象并且在 spring 容器内注册。

遵循规则:

mapper.java 和 mapper.xml 映射文件名一样,且必须在同一目录下;自动扫描出来的 bean 的 id 为 mapper 类的名(首字母小写);当扫描包有多个时,用逗号隔开。

 

 

四、总结

推荐 用 MapperScannerConfigurer 自动扫描和注册 来开发。

 

源代码:案例源码