qileilove

          blog已經(jīng)轉(zhuǎn)移至github,大家請訪問 http://qaseven.github.io/

          Mybatis通用操作數(shù)據(jù)庫方法類總結(jié)

           在項目中用到myBatis作為orm框架,與spring結(jié)合,通常的做法是寫一個通用的數(shù)據(jù)庫操作類,包括對數(shù)據(jù)庫的增、刪、改、查操作。
            具體的實現(xiàn)類如下:
          import java.sql.Connection;
          import java.sql.ResultSet;
          import java.sql.ResultSetMetaData;
          import java.sql.SQLException;
          import java.sql.Statement;
          import java.util.ArrayList;
          import java.util.HashMap;
          import java.util.List;
          import java.util.Map;
          import org.apache.log4j.Logger;
          import org.mybatis.spring.SqlSessionTemplate;
          import org.mybatis.spring.SqlSessionUtils;
          import org.railway.com.trainplan.entity.QueryResult;
          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.stereotype.Repository;
          import org.springframework.util.Assert;
          /**
          * 基礎(chǔ)框架的數(shù)據(jù)訪問層抽象實現(xiàn)類myBatis orm框架,
          * 所有模塊的數(shù)據(jù)訪問層實現(xiàn)類均繼承該類。<br>
          *
          * JDK版本:JDK1.6
          * @version 1.0
          */
          @Repository
          public class BaseDao {
          private static final Logger log = Logger.getLogger(BaseDao.class);
          @Autowired
          public SqlSessionTemplate sqlSession;
          /**
          * 獲取數(shù)據(jù)庫連接對象
          * @return
          */
          private Connection getConnection(){
          Connection connection = SqlSessionUtils.getSqlSession(
          sqlSession.getSqlSessionFactory(), sqlSession.getExecutorType(),
          sqlSession.getPersistenceExceptionTranslator()).getConnection();
          return connection;
          }
          //=================================以下代碼為myBatis實現(xiàn)的常用方法(后綴加BySql)===========================//
          /**
          * 往庫表中插入記錄
          * @param statementId 調(diào)用myBatis的mapper文件的聲明段名,
          * 規(guī)則名:mapper的namespace+"." + 該mapper文件某片段的id
          * @param value 要操作的對象
          * @return 插入成功的記錄數(shù)
          */
          public int insertBySql(String statementId, Object value) {
          return sqlSession.insert(statementId, value);
          }
          /**
          * 刪除庫表中的記錄(可批量刪除),返回刪除成功的記錄數(shù)。
          *
          * @param statementId 調(diào)用myBatis的mapper文件的聲明段名,
          * 規(guī)則名:mapper的namespace+"." + 該mapper文件某片段的id
          * @param value  刪除條件值
          * @return 刪除成功的記錄數(shù)
          */
          public int deleteBySql(String statementId, Object value) {
          return sqlSession.delete(statementId, value);
          }
          /**
          * 更新庫表中的記錄(可批量更新),返回更新成功的記錄數(shù)。
          *
          * @param statementId 調(diào)用myBatis的mapper文件的聲明段名,
          * 規(guī)則名:mapper的namespace+"." + 該mapper文件某片段的id
          * @param value       更新條件值值
          * @return 更新成功的記錄數(shù)
          */
          public int updateBySql(String statementId, Object value) {
          return sqlSession.update(statementId, value);
          }
          /**
          * 查詢符合條件的記錄,生成List返回。
          *
          * @param statementId 調(diào)用myBatis的mapper文件的聲明段名,
          * 規(guī)則名:mapper的namespace+"." + 該mapper文件某片段的id
          * @param value       查詢條件值
          * @return list       找到的記錄
          */
          public List selectListBySql(String statementId, Object value) {
          List list = sqlSession.selectList(statementId, value);
          //數(shù)據(jù)庫含有空格的字段值(char類型),裝載到myBatis生成的持久對象屬性中,是否自動去掉屬性值左右兩邊的空格
          //如果需要去掉空格,則使用如下方式
          //list = Config.getPropertyBool("po.propertyvalue.trimable", true) ? BeanUtil.trim(list) : list
          return list;
          }
          /**
          * 查詢單個符合條件的記錄,生成Object返回</br>
          * @param statementId 調(diào)用myBatis的mapper文件的聲明段名,
          * 規(guī)則名:mapper的namespace+"." + 該mapper文件某片段的id
          * @param parameter   查詢條件值
          * @return list 找到的記錄
          */
          public Object selectOneBySql(String statementId, Object parameter) {
          Object bean = sqlSession.selectOne(statementId, parameter);
          //數(shù)據(jù)庫含有空格的字段值(char類型),裝載到myBatis生成的持久對象屬性中,是否自動去掉屬性值左右兩邊的空格
          //如果需要去掉空格,則使用如下方式
          //bean = Config.getPropertyBool("po.propertyvalue.trimable", true) ? BeanUtil.trim(bean) : bean
          return bean;
          }
          /**
          * myBatis分頁查詢符合條件的記錄
          * <p>
          * 注意:調(diào)用該方法,必須在myBatis的mapper文件中存在statementId_COUNT片段</br>
          * <b>特別說明:由于該命令采用的分頁技術(shù)不是數(shù)據(jù)庫本身的分頁技術(shù),而是采用ResultSet的absolute定位技術(shù),<br>
          * 需要把查詢結(jié)果全部裝入ResultSet再定位。如果查詢結(jié)果較大(1萬條記錄以上),效率會很低。<br>
          * 建議使用Hibernate的query方法或在mapper的XML中使用數(shù)據(jù)庫內(nèi)部分頁技術(shù)<br>
          * (即把pageId,pageSize作為參數(shù)傳入SQL語句的類似limit n,m中)來查詢。
          * </b>
          * </p>
          * @param statementId 調(diào)用myBatis的mapper文件的聲明段名,規(guī)則名:mapper的namespace+"." + 該sqlMap文件某片段的id
          * @param parameter   查詢條件對象
          * @param offset       返回查詢結(jié)果的起始行,從0開始
          * @param pageSize        返回查詢結(jié)果的最大行數(shù)
          * @throws com.fbd.crm.exception.BaseUncheckedException
          * @return com.fbd.crm.common.QueryResult
          */
          @SuppressWarnings({ "rawtypes", "unchecked" })
          public QueryResult selectListForPagingBySql(String statementId, Object parameter) throws Exception{
          Assert.hasText(statementId, "傳入的SQL配置ID不能為空.");
          //計算總頁數(shù)
          Integer count = null;
          try {
          count = (Integer)sqlSession.selectOne(statementId + "_COUNT", parameter);
          } catch (Exception e) {
          String msg = "配置文件中不存在COUNT語句或發(fā)生其它例外,無法執(zhí)行總數(shù)統(tǒng)計. SqlMap id:" + statementId;
          log.error(msg, e);
          throw new Exception(e);
          }
          if ((count == null) || (count.intValue() <= 0)) {
          log.info("執(zhí)行COUNT后,返回的結(jié)果數(shù)為0,表示該SQL執(zhí)行無結(jié)果數(shù)據(jù)返回.因此提前終止其數(shù)據(jù)查詢并立即返回空集.");
          return new QueryResult(new ArrayList(), 0);
          }
          List resultList = sqlSession.selectList(statementId, parameter);
          QueryResult result = new QueryResult(resultList, count);
          return result;
          }
          /**
          * myBatis帶匯總查詢
          * </b>
          * </p>
          * @param statementId 調(diào)用myBatis的mapper文件的聲明段名,規(guī)則名:mapper的namespace+"." + 該sqlMap文件某片段的id
          * @param parameter   查詢條件對象
          * @throws com.fbd.crm.exception.BaseUncheckedException
          * @return com.fbd.crm.common.QueryResult
          */
          public QueryResult selectListWithTotal(String statementId, Object parameter) throws Exception{
          Assert.hasText(statementId, "傳入的SQL配置ID不能為空.");
          //計算總頁數(shù)
          Integer count = null;
          try {
          count = (Integer)sqlSession.selectOne(statementId + "_COUNT", parameter);
          } catch (Exception e) {
          String msg = "配置文件中不存在COUNT語句或發(fā)生其它例外,無法執(zhí)行總數(shù)統(tǒng)計. SqlMap id:" + statementId;
          log.error(msg, e);
          throw new Exception(e);
          }
          if ((count == null) || (count.intValue() <= 0)) {
          log.info("執(zhí)行COUNT后,返回的結(jié)果數(shù)為0,表示該SQL執(zhí)行無結(jié)果數(shù)據(jù)返回.因此提前終止其數(shù)據(jù)查詢并立即返回空集.");
          return new QueryResult(new ArrayList(),new ArrayList(), 0);
          }
          List resultList = sqlSession.selectList(statementId, parameter);
          List totalList = sqlSession.selectList(statementId + "_TOTAL", parameter);
          QueryResult result = new QueryResult(resultList, totalList, count);
          return result;
          }
          /**
          * 執(zhí)行sql
          * @category 該事務(wù)不在spring事務(wù)管理機制內(nèi)
          * @param sql
          * @return List
          * @throws SQLException
          */
          public List executeQueryBySql(String sql) throws SQLException{
          Connection con = null;
          Statement stmt = null;
          List list = new ArrayList();
          try {
          con = this.getConnection();//sqlSession.getConnection();
          con.setAutoCommit(false);
          stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
          ResultSet rSet = stmt.executeQuery(sql);
          ResultSetMetaData md = rSet.getMetaData();
          int num = md.getColumnCount();
          while (rSet.next()) {
          Map mapOfColValues = new HashMap(num);
          for (int i = 1; i <= num; i++) {
          mapOfColValues.put(md.getColumnName(i), rSet.getObject(i));
          }
          list.add(mapOfColValues);
          }
          con.commit();
          } catch (Exception e) {
          e.printStackTrace();
          throw new SQLException("sql執(zhí)行失敗");
          }finally {
          if (stmt != null) {
          stmt.close();
          }
          // 此處不關(guān)閉,連接關(guān)閉由org.springframework.jdbc.datasource.DataSourceTransactionManager自動完成
          if (con != null) {
          con.close();
          }
          }
          return list;
          }
          }
          采用的myBatis版本和Maven配置:
          <!-- mybatis -->
          <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.2.7</version>
          </dependency>
          <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.2.2</version>
          </dependency>
            3.怎么調(diào)用
            在service中將上面的BaseDao類注入就可以調(diào)用了它的方法了。比如:
          @Autowired
          private BaseDao baseDao;

          posted on 2014-06-20 13:22 順其自然EVO 閱讀(799) 評論(0)  編輯  收藏 所屬分類: selenium and watir webdrivers 自動化測試學習

          <2014年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          導(dǎo)航

          統(tǒng)計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 曲麻莱县| 临沭县| 柏乡县| 喜德县| 西畴县| 禹城市| 宾川县| 忻城县| 广西| 张北县| 奉新县| 济源市| 澎湖县| 太保市| 东城区| 长子县| 陈巴尔虎旗| 郧西县| 巴林右旗| 马鞍山市| 乳山市| 镇赉县| 历史| 栖霞市| 呼伦贝尔市| 鄂托克前旗| 陵水| 宣威市| 呼玛县| 新竹市| 福清市| 威信县| 军事| 河曲县| 盐亭县| 玉溪市| 墨玉县| 古交市| 广丰县| 利辛县| 连江县|