Ibatis相关基础之一-为什么要用sqlMapClientTemplate

来源:互联网 发布:mac战网外服 编辑:程序博客网 时间:2024/06/05 14:11

Ibatis中最常用的类是SqlMapClientTemplate,它封装了SqlMapClient,我们在做数据库操作的时候通常都是用SqlMapClientTemplate类。通过如下配置文件:

<bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.sqlMapClientTemplate<span style="font-family: Arial, Helvetica, sans-serif;">"></span><property name="sqlMapClient" ref="sqlMapClient" /></bean><bean id="sqlMapClient"class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"><property name="configLocation"><value>classpath:sqlmap.xml</value></property><property name="dataSource" ref="dataSource" /></bean>

就可以声明一个SqlMapClientTemplate的bean。

那么,为什么要用SqlMapClientTemplate而不使用SqlMapClient。因为

1)SqlMapClientTemplate可以帮我们统一抛出的异常类型为DataAccessException

2)管理Session的生命周期。每次执行CRUD操作时,都会调用execute(SqlMapClientCallback<T> action)方法,该方法负责创建并关闭session。

3)除此之外,如果使用SqlMapClient的insert/update/delete/query方法,它将会直接调用其父接口SqlMapExecutor的相应方法;而若使用SqlMapClientTemplate的insert/update/delete/query,将使用该类自己定义的相应方法,这些方法来自于 org.springframework.orm.ibatis.SqlMapClientTemplate这个类,是完全基于Spring的,而com.ibatis.sqlmap.client.SqlMapExecutor是基于ibatis的。

在批量操作时,为了提高性能,我们通常采用批量执行。那么,借助于SqlMapClientTemplate我们如何实现批量执行呢?

getSqlMapClientTemplate().execute(new SqlMapClientCallback() {         public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {                 executor.startBatch();                 executor.update("insertSomething", "myParamValue");                 executor.update("insertSomethingElse", "myOtherParamValue");                 executor.executeBatch();                 return null;         } });
很简单吧。那么,以后再用Itatis时请使用SqlMapClientTemplate吧。

0 0
原创粉丝点击