Loading

Spring整合Mybatis(方式二)

抽象方法的实现类直接继承SqlSessionDaoSupport类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate

image
测试:

1、将我们上面写的UserDaoImpl修改一下

public class UserMapper2Impl extends SqlSessionDaoSupport implements UserMapper {
    public List<User> selectUser() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

2、修改bean的配置

<bean id="userMapper2" class="com.zhang.mapper.userMapper2Impl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

3、测试

@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    UserMapper mapper = (UserMapper) context.getBean("userMapper2");
    List<User> user = mapper.selectUser();
    System.out.println(user);
}

总结 : 整合到spring以后可以完全不要mybatis的配置文件,除了这些方式可以实现整合之外,我们还可以使用注解来实现,具体请看springboot部分

posted @ 2022-03-30 15:37  Cn_FallTime  阅读(53)  评论(0编辑  收藏  举报