ITeye博客

ibatis学习(三)---ibatis与spring的整合

lzth · 2011-07-07 15:13 · 编程语言 · Markdown

[code="java"] Spring通过DAO模式,提供了对iBATIS的良好支持。SqlMapClient对象是iBATIS中的主要对象,我们可以通过配置让spring来管理SqlMapClient对象的创建。 与hibernate类似,Spring 提供了SqlMapClientDaoSupport对象,我们的DAO可以继承这个类,通过它所提供的SqlMapClientTemplate对象来操纵数据库。看起来这些概念都与hibernate类似。 通过SqlMapClientTemplate来操纵数据库的CRUD是没有问题的,这里面关键的问题是事务处理。Spring提供了强大的声明式事务处理的功能,我们已经清楚hibernate中如何配置声明式的事务,那么在iBATIS中如何获得声明式事务的能力呢? 第一,我们需要了解的是spring通过AOP来拦截方法的调用,从而在这些方法上面添加声明式事务处理的能力。典型配置如下:applicationContext-common.xml 这些事务都是声明在业务逻辑层的对象上的。 第二,我们需要一个事务管理器,对事务进行管理。 此后,我们需要让spring来管理SqlMapClient对象: classpath:sqlMapConfig.xml 我们的sqlMapConfig.xml就可以简写为: User.xml:如下 select * from t_user select * from t_user where id=#id# insert into t_user values ( null,#username#,#password# ) update t_user set username = #username#,password=#password# where id=#id# delete from t_user where id=#id# 我们的DAO的编写: package com.iabtis.dao.impl.ibatis; import java.util.List; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.ibatis.dao.UserDAO; import com.ibatis.crm.model.User; public class UserDAOImpl extends SqlMapClientDaoSupport implements UserDAO { public void select(User user) { getSqlMapClientTemplate().delete("selectUser ",user.getId()); } public List findAll() { return getSqlMapClientTemplate().queryForList("selectAllUsers "); } public void delete(User user) { getSqlMapClientTemplate().delete("deleteUser ",user.getId()); } public void save(User user) { getSqlMapClientTemplate().insert("insertUser ",user); } public void update(User user) { getSqlMapClientTemplate().update("updateUser ",user); } } 继承SqlMapClientDaoSupport,要求我们注入SqlMapClient对象,因此,需要有如下的DAO配置: 这就是所有需要注意的问题了,此后就可以在业务逻辑层调用DAO对象了! [/code]

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。