首页 > 编程语言 > Spring如何集成ibatis项目并实现dao层基类封装
2020
10-10

Spring如何集成ibatis项目并实现dao层基类封装

Apache iBatis(现已迁至Google Code下发展,更名为MyBatis)是当前IT项目中使用很广泛的一个半自动ORM框架,区别于Hibernate之类的全自动框架,iBatis对数据库的操作拥有更加灵活的控制,对于那些经常需要调用本地数据库函数自定义SQL语句,或是喜欢自己优化SQL执行效率的开发者来说,iBatis是一个非常不错的选择。

而得到广泛应用的开源企业架构SpringFramework,也很好的将其进行了集成,使得iBatis在 SpringFramework中的使用更加便利、快捷。开发者所要做的就是继承SpringFramework中提供的SqlMapClientDaoSupport类即可。下面将简单介绍使用spring中集成的ibatis进行项目中dao层基类封装,以方便开发。

1、SqlMapClientFactoryBean 的装配

  SqlMapClientFactoryBean是SqlMapClientTemplate使用的基础,如果在SpringFramework应用中没有装配SqlMapClientFactoryBean,那么SqlMapClientTemplate将不可用,报空指针错误。其配置信息如下:

<bean id="sqlMapClient"
  class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
  <!-- iBatis sqlmap config 文件位置 -->
  <property name="configLocation">
    <value>
      /WEB-INF/classes/org/bussiness/config/ibatis/SqlMapConfig.xml
    </value>
  </property>
  <!-- 在SpringFramework配置文件中使用的数据源 -->
  <property name="dataSource">
    <ref local="dataSource" />
  </property>
  <!-- 如果需要读写Lob字段,需要注入在SpringFramework配置文件中配置好的Handler,这里是Oracle的数据库 -->
  <property name="lobHandler" ref="oracleLobHandler"/>
</bean>

2、继承使用SqlMapClientDaoSupport类

2.1)首先定义一个IBaseDao接口提供各种场景的查询、修改、删除、分页查询的各种抽象功能方法

package org.biframework.dao.ibatis;
import com.ibatis.common.util.PaginatedList;
import java.util.List;
import org.biframework.exception.DaoException;
public abstract interface IBaseDao
{
 public abstract Object getObject(String paramString, Object paramObject)
  throws DaoException;

 @SuppressWarnings("unchecked")
 public abstract List getList(String paramString, Object paramObject)
  throws DaoException;

 public abstract PaginatedList getPgntList(String paramString1, Object paramObject, String paramString2)
  throws DaoException;

 public abstract PaginatedList getPgntList(String paramString1, Object paramObject, String paramString2, int paramInt)
  throws DaoException;

 @SuppressWarnings("unchecked")
 public abstract List getListUseSameStmt(String paramString, Object[] paramArrayOfObject)
  throws DaoException;

 public abstract int update(String paramString, Object paramObject)
  throws DaoException;

 public abstract int transUpdateSameOpt(String paramString, Object[] paramArrayOfObject)
  throws DaoException;

 public abstract int transUpdate(Object[][] paramArrayOfObject)
  throws DaoException;
 
 @SuppressWarnings("unchecked")
 public List getList(String statementName, Object parameterObject,
      int skipResults, int maxResults) throws DaoException;
}

备注:该层也可以不写

2.2)继承使用SqlMapClientDaoSupport类并实现IBaseDao接口

package org.biframework.dao.ibatis;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.biframework.exception.DaoException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.common.util.PaginatedList;

public class BaseDao extends SqlMapClientDaoSupport implements IBaseDao {

  @SuppressWarnings("unused")
  private static Log log;
  protected static final int PAGE_SIZE = 15;
  @SuppressWarnings("unchecked")
  static Class class$0; /* synthetic field */

  public BaseDao() {
  }
  /*
  使用spring中集成的ibatis实现数据的查询、修改、删除
  1)当请求参数被封装为一个普通对象,查询结果为List集合:
  使用queryForList返回List 源码方法如下:getSqlMapClientTemplate(),获取SqlMapClientTemplate对象,
  参数说明:a、statementName sql声明;b、parameterObject请求参数对象 queryForList方法源码如下
  public List queryForList(String statementName, Object parameterObject)
   throws DataAccessException
   {
    executeWithListResult(new SqlMapClientCallback()
    {
     private final String val$statementName;
     private final Object val$parameterObject;
     public Object doInSqlMapClient(SqlMapExecutor executor)
      throws SQLException
     {
      return executor.queryForList(this.val$statementName, this.val$parameterObject);
     }
    });
   }
  */
  @SuppressWarnings("unchecked")
  public List getList(String statementName, Object parameterObject)
      throws DaoException {
    List list = getSqlMapClientTemplate().queryForList(statementName,
        parameterObject);
    return list;
  }
  
  /*
  2)当请求参数被封装为一个数组对象时:
    即使用数组存放多个传参对象(obj1、obj2...)而后使用相同sql,进行多次查询,将多次查询的结果list1、list2...放到结果集List中)
  使用queryForList返回List 封装的方法如下:
  */
  @SuppressWarnings("unchecked")
  public List getListUseSameStmt(String statementName, Object objectParam[])
      throws DaoException {
    List list = null;
    List temp = null;
    if (statementName == null || objectParam == null|| objectParam.length == 0){
      return list;
    }else{
      for (int i = 0; i < objectParam.length; i++) {
        if (list == null){
          list = new ArrayList();
          temp = getSqlMapClientTemplate().queryForList(statementName,objectParam[i]);
        }  
        if (temp != null){
          list.addAll(temp);
        }  
      }
    }
    return list;
  }

  /*
  3)当请求参数被封装为一个普通对象,查询结果为Object对象
  */
  @SuppressWarnings("unchecked")
  public Object getObject(String statementName, Object parameterObject)
      throws DaoException {
    Object result = null;
    List list = getSqlMapClientTemplate().queryForList(statementName,parameterObject);
    if (list != null && list.size() > 0){
      result = list.get(0);
    }
    return result;
  }
  
  /*
  4)ibatis-common-2.jar、使用ibatis自身封装的PaginatedList工具类进行分页查询,每页15条数据。
  public PaginatedList queryForPaginatedList(String statementName, Object parameterObject, int pageSize)
  throws DataAccessException
   {
    if (((this.sqlMapClient instanceof ExtendedSqlMapClient)) && (((ExtendedSqlMapClient)this.sqlMapClient).getDelegate().getTxManager() == null)) {
     throw new InvalidDataAccessApiUsageException("SqlMapClient needs to have DataSource to allow for lazy loading - specify SqlMapClientFactoryBean's 'dataSource' property");
    }
    (PaginatedList)execute(new SqlMapClientCallback()
    {
     private final String val$statementName;
     private final Object val$parameterObject;
     private final int val$pageSize;
     
     public Object doInSqlMapClient(SqlMapExecutor executor)
      throws SQLException
     {
      return executor.queryForPaginatedList(this.val$statementName, this.val$parameterObject, this.val$pageSize);
     }
    });
   }
  */
  public PaginatedList getPgntList(String statementName,
      Object parameterObject, String pageDirection) throws DaoException {
    PaginatedList list = getSqlMapClientTemplate().queryForPaginatedList(
        statementName, parameterObject, 15);
    if ("next".equals(pageDirection))
      list.nextPage();
    else if ("previous".equals(pageDirection))
      list.previousPage();
    else if ("first".equals(pageDirection))
      list.isFirstPage();
    else if ("last".equals(pageDirection))
      list.isLastPage();
    return list;
  }

  /*
  4)自己指定分页查询的数量
  */
  public PaginatedList getPgntList(String statementName,
      Object parameterObject, String pageDirection, int pageSize)
      throws DaoException {
    PaginatedList list = getSqlMapClientTemplate().queryForPaginatedList(
        statementName, parameterObject, pageSize);
    if ("next".equals(pageDirection)) {
      System.out.println("下一页");
      list.nextPage();
    } else if ("previous".equals(pageDirection)) {
      System.out.println("上一页");
      list.previousPage();
    } else if ("first".equals(pageDirection)) {
      System.out.println("首页");
      list.isFirstPage();
    } else if ("last".equals(pageDirection)) {
      System.out.println("末页");
      list.isLastPage();
    }
    return list;
  }
  
  /*
  5)该方法暂时未理解其主要是处于何种场景使用
  */
  public int update(String statementName, Object parameterObject)
  throws DataAccessException
   {
    Integer result = (Integer)execute(new SqlMapClientCallback()
    {
     private final String val$statementName;
     private final Object val$parameterObject;
     public Object doInSqlMapClient(SqlMapExecutor executor)
      throws SQLException
     {
      return new Integer(executor.update(this.val$statementName, this.val$parameterObject));
     }
    });
    return result.intValue();
   }  
  */
  public int transUpdate(Object statementAndparameter[][])
      throws DaoException {
    Object statements[] = statementAndparameter[0];
    Object parameters[] = statementAndparameter[1];
    int result = 0;
    for (int i = 0; i < statements.length; i++) {
      String name = (String) statements[i];
      Object param = parameters[i];
      result += getSqlMapClientTemplate().update(name, param);
    }
    return result;
  }

  /*
  6)请求参数被封装为一个数组对象,返回结果为成功更新的记录数使用spring封装的update方法进行更新操作
  */
  public int transUpdateSameOpt(String statementName, Object objectParam[])
      throws DaoException {
    int result = 0;
    if (statementName == null || objectParam == null
        || objectParam.length == 0)
      return result;
    for (int i = 0; i < objectParam.length; i++)
      result += getSqlMapClientTemplate().update(statementName,
          objectParam[i]);
    return result;
  }
  /*
  7)请求参数被封装为一个普通对象,返回结果为成功更新的记录数
  */
  public int update(String statementName, Object parameterObject)
      throws DaoException {
    int result = getSqlMapClientTemplate().update(statementName,
        parameterObject);
    return result;
  }

  static {
    log = LogFactory.getLog(org.biframework.dao.ibatis.BaseDao.class);
  }
  
  /*
  8)请求参数被封装为一个普通对象,并对查询的结果记录指定跳跃数和最大结果集
  */
  @SuppressWarnings("unchecked")
  public List getList(String statementName, Object parameterObject,
      int skipResults, int maxResults) throws DaoException {
    return getSqlMapClientTemplate().queryForList(statementName,
        parameterObject, skipResults, maxResults);
  }
}

3、进行dao层配置,并进行查询等操作

3.1)所有的dao层都继承BaseDao类

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.biframework.dao.ibatis.BaseDao;
import org.biframework.exception.DaoException;
import org.bussiness.product.detailquery.bo.StPolicyBean;

public class StPolicyDao extends BaseDao {
  protected static Log log = LogFactory.getLog(StPolicyDao.class);
  
  @SuppressWarnings("unchecked")
  public List getStPerm(StPBean param) throws DaoException{
    return super.getList("getShortPrem", param);
  }

  public Object getStPermCount(StPBean param) throws DaoException{
    return super.getObject("getShortPremCount", param);
  }
  }
}

3.2)进行dao装配 detailQuery-applicationContext.xml

<bean id="nstpDao" class="org.bussiness.product.detailquery.dao.NstPolicyDao">
  <property name="dataSource">
    <ref bean="dataSource" />
  </property>
  <property name="sqlMapClient">
    <ref bean="sqlMapClient" />
  </property>
</bean>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧