mybatis-spring整合总结05_Injecting Mappers
Injecting MappersDAO除了手动使用SqlSessionDaoSupport或是SqlSessionTemplate之外,Mybatis-Spring提供了另外一种方法,使用代理工厂—MapperFactoryBean。它允许你直接将map接口注入到Service beans中去,而不用编写实现类(DAOImpl)。因为Mybatis-Spring会为你创建代理。
将mapper加入Spring的配置方法:
Java代码
[*]<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
[*]<property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
[*]<property name="sqlSessionFactory" ref="sqlSessionFactory" />
[*]</bean>
MapperFactoryBean将自动创建一个实现了UserMapper的代理类并注入到应用中。因为是在运行时创建,所以Mapper必须是一个接口而不是实现类。
Java代码
[*]<bean id="fooService" class="org.mybatis.spring.sample.mapper.FooServiceImpl">
[*]<property name="userMapper" ref="userMapper" />
[*]</bean>
Java代码
[*]public class FooServiceImpl implements FooService {
[*]private UserMapper userMapper;
[*]public void setUserMapper(UserMapper userMapper) {
[*]this.userMapper = userMapper;
[*]}
[*]public User doSomeBusinessStuff(String userId) {
[*]return this.userMapper.getUser(userId);
[*]}
[*]}
Mybatis-Spring将会管理事务的commit,rollback,close
页:
[1]