为了代替手工使用SqlSessionDaoSupport或SqlSessionTemplate编写数据访问对象(DAO)的代码,MyBatis-Spring提供了一个动态代理的实现——MapperFactoryBean。这个类可以让你直接注入数据映射器量化接口,接口到你的service层bean中。当使用映射器时,你仅仅如调用你的DAO一样调用它们就可以了,但是你不需要编写任何DAO实现的代码,因为MyBatis-Spring将会为你创建代理。同样,MapperFactoryBean创建的代理控制开放和关闭session。
在使用MapperFactoryBean时,可以通过映射量化接口,接口方式提供sql语句,也可以通过映射文件提供sql语句。
package cn.edu.nuc.dao;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import cn.edu.nuc.bean.User;
public interface UserMapper {
@Select('SELECT * FROM user WHERE id = #{id}')
User getUser(@Param('id') long id);
}
可以不用dao层,直接把数据映射器Mapper接口注入到service层
packagecn.edu.nuc.service.impl;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Service;
importcn.edu.nuc.bean.User;
importcn.edu.nuc.dao.UserMapper;
importcn.edu.nuc.service.UserService;
@Service
public classUserServiceImpl implements UserService {
@Autowired
privateUserMapper userMapper;
publicUser getUserById(Long id) {
returnuserMapper.getUser(id);
}
}
MapperFactoryBean创建的代理类实现了UserMapper接口,并且注入到应用程序中。因为代理创建在运行时环境中(Runtime,译者注),那么指定的映射器必须是一个接口,而不是一个具体的实现类。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.edu.nuc.bean.User;
import cn.edu.nuc.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({'classpath:spring.xml'})
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void getUserTest() {
Long id = 1L;
User user = userService.getUserById(id);
System.out.println(user.getName());
}
}
分析:
MapperFactoryBean创建的代理类实现了UserMapper接口,并且注入到应用程序中。因为代理创建在运行时环境中(Runtime,译者注),那么指定的映射器必须是一个接口,而不是一个具体的实现类。
数据映射器接口UserMapper不需要显示写一个注解交给spring管理,然后在service层进行注入;因为UserMapper接口其实是供MapperFactoryBean创建的代理类来实现的,然后自动放到spring的ioc容器中,在Service实现中注入的是MapperFactoryBean创建的代理类;
补充:
没有必要在Spring的XML配置文件中注册所有的映射器。相反,你可以使用一个MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean。要创建MapperScannerConfigurer,可以在Spring的配置中添加如下代码:
basePackage属性是让你为映射器接口文件设置基本的包路径。你可以使用分号或逗号作为分隔符设置多于一个的包路径。每个映射器将会在指定的包路径中递归地被搜索到。
上面spring配置文件可以改成如下:
没有必要去指定SqlSessionFactory或SqlSessionTemplate,因为MapperScannerConfigurer将会创建MapperFactoryBean,之后自动装配。但是,如果你使用了一个以上的DataSource,那么自动装配可能会失效。这种情况下,你可以使用sqlSessionFactoryBeanName或sqlSessionTemplateBeanName属性来设置正确的bean名称来使用。这就是它如何来配置的,注意bean的名称是必须的,而不是bean的引用,因此,value属性在这里替代通常的ref:
MapperScannerConfigurer支持过滤由指定的创建接口或注解创建映射器。annotationClass属性指定了要寻找的注解名称。markerInterface属性指定了要寻找的父接口。如果两者都被指定了,加入到接口中的映射器会匹配两种标准。默认情况下,这两个属性都是null,所以在基包中给定的所有接口可以作为映射器加载。
MapperScannerConfigurer其实和MapperFactoryBean类似,都是创建代理然后注入到spring中;区别是前者是自动扫描数据映射器接口,生成代理类、并注入到Spring的容器中;
文章为作者独立观点,不代表 股票程序化软件自动交易接口观点