注:该bean负责调用SqlSession的getMapper方法,获得 符合Mapper映射器要求的对象。并且会将这些对象放到spring 容器里面(默认的id是首字母小写之后的接口名,比如Mapper 映射器名为EmpDAO,则默认的id是empDAO,也可以使用@Repository 来修改默认的id)。
注:如果只扫描特定的映射器,可以做如下两步。
step1.开发一个注解,比如@MyBatisRepository,并且,将 该注解添加到需要扫描的映射器上面。


step2.给MapperScannerConfigurer注入annotationClass属性值。 


代码如下:

自己写一个注解:

package annotations;

public @interface MyBatisRepository {

}


spring配置文件中的MapperScannerConfigurer

<!-- 配置MapperScannerConfigurer -->
	<!-- 
		获得符合Mapper映射器要求的对象(相当于调用SqlSession的getMapper()方法)。
		并且会将这些对象放到spring容器里面(默认的id是首字母小写之后的接口名
		比如Mapper映射器名为EmpDAO,则默认的id是empDAO,也可以使用@Repository来修改默认的id
	 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	  <!-- 扫描该包及其子包下的所有映射器 -->
	  <property name="basePackage" value="dao"/>
	  <!-- 只扫描特定的接口 -->
	  <!-- 含有特定注解的接口 -->
	  <property name="annotationClass" value="annotations.MyBatisRepository"/>
	</bean>

在映射器前面加入特定的注解

package dao;

import java.util.List;

import annotations.MyBatisRepository;
import entity.Dept;
@MyBatisRepository//扫描特定注解的接口
public interface DeptDAO {
	public void save(Dept dept);//插入一条数据
	public List<Dept> findAll();//查询所有记录
	public Dept findById(int id);//根据id查询一条记录
	public void modify(Dept dept);//修改一条记录 
	public void delete(int id);//删除一条记录
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐