Dao操作的抽取—封裝BaseDao

普通Dao操作通用步驟

1.寫SQL語句
2.獲取連接
3.創(chuàng)建PreparedStatement
4.執(zhí)行sql語句

a)更新
b)查詢

5.關(guān)閉/異常

BaseDao的實(shí)現(xiàn)

BaseDao是自己寫的通用的dao父類,自己寫的所有的dao都繼承這個(gè)父類dao

通用方法
  • 更新類別的:update , delete , insert
  • 查詢類別的
代碼中用到元數(shù)據(jù)方法簡(jiǎn)書地址:數(shù)據(jù)庫(kù)之元數(shù)據(jù)——DatabaseMetaData
package com.eu.dss.dao;

import com.eu.dss.util.ConnUtil;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import java.sql.*;
import java.util.ArrayList;

/**
 * Created by 馬歡歡 on 2017/5/18.
 */
public class BaseDao {
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;

    /**
     * 更新的通用方法
     * 更新的sql語句(update/insert/delete)
     * paramsValue  sql語句中占位符對(duì)應(yīng)的值(如果沒有占位符,傳入null)
     */
    public void update(String sql, Object[] paramsValue) {
        try {
            //獲取連接
            conn = ConnUtil.getConnextion();
            //創(chuàng)建執(zhí)行任務(wù)
            pstmt = conn.prepareStatement(sql);
            //參數(shù)元數(shù)據(jù): 得到占位符參數(shù)的個(gè)數(shù)
            int count = pstmt.getParameterMetaData().getParameterCount();
            //判斷是否有條件
            if (paramsValue != null && paramsValue.length > 0) {
                //循環(huán)給參數(shù)賦值
                for (int i = 0; i < count; i++) {
                    pstmt.setObject(i + 1, paramsValue[i]);
                }
            }
            pstmt.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            ConnUtil.close(null, pstmt, conn);

        }
    }

    /**
     * 查詢通用方法
     */
    public <T> List<T> query (String sql, Object[] paramsValue , Class<T> tClass){
        List <T> list = new ArrayList<T>();
        //獲取連接
        conn = ConnUtil.getConnextion();
        try {
            //創(chuàng)建對(duì)象
            pstmt = conn.prepareStatement(sql);
            int count = pstmt.getParameterMetaData().getParameterCount();
            if(paramsValue !=null && paramsValue.length> 0 ){
                for(int i=0;i<paramsValue.length;i++){
                    pstmt.setObject(i+1,paramsValue[i]);
                }
            }
            rs = pstmt.executeQuery();
            //拿到結(jié)果集元數(shù)據(jù)
            ResultSetMetaData rsmd = rs.getMetaData();
            //獲取列的個(gè)數(shù)
            int culumnCount =rsmd.getColumnCount();
            T t;
            while(rs.next()){
                t = tClass.newInstance();
                for (int i = 0; i<culumnCount;i++){
                    String coulumnName =rsmd.getColumnName(i+1);
                    Object value = rs.getObject(coulumnName);
                    BeanUtils.copyProperty(t,coulumnName,value);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

DAO層: 下來我們?cè)趯慏ao層的代碼時(shí)就特別簡(jiǎn)單

下面示例:

  • 查詢數(shù)據(jù)
  • 查找數(shù)據(jù)按照id
  • 插入數(shù)據(jù)
  • 更新數(shù)據(jù)
  • 刪除數(shù)據(jù)
package com.eu.dss.dao.impl;

import com.eu.dss.dao.BaseDao;
import com.eu.dss.dao.ITronClassDao;
import com.eu.dss.entity.TronClasstype;
import net.sf.json.JSONArray;

import java.util.List;

/**
 * Created by 馬歡歡 on 2017/5/23.
 */
public class TronClassDao extends BaseDao implements ITronClassDao  {

    public List<TronClasstype> TronClasstype() {
        String sql = " SELECT * FROM eu_tronclass ; ";
        List <TronClasstype> list = super.query(sql,null,TronClasstype.class);
        JSONArray jsonArray = JSONArray.fromObject(list);
        System.out.println("bbbb"+jsonArray);
        return list;
    }

    public TronClasstype findByid(int id) {
        String sql = " SELECT * FROM eu_tronclass where id=? ; ";
        List <TronClasstype> list = super.query(sql,new Object[id],TronClasstype.class);
        return (list!=null && list.size()>0) ? list.get(0) : null;
    }

    public void save(TronClasstype tronClassType) {
        String sql = " INSERT INTO eu_tronclass (year,tron_month,eu_rj,eu_xin,eu_rw,eu_ts,eu_xiu,eu_gz,eu_kuai,eu_ad,eu_wc,eu_wu,eu_jr) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?); ";
        Object[] paramsValue = {tronClassType.getYear(),tronClassType.getTron_month(),
                tronClassType.getEu_rj(),   tronClassType.getEu_xin(),
                tronClassType.getEu_rw(),   tronClassType.getEu_ts(),
                tronClassType.getEu_xiu(),  tronClassType.getEu_gz(),
                tronClassType.getEu_kuai(), tronClassType.getEu_ad(),
                tronClassType.getEu_wc(),   tronClassType.getEu_wu(),
                tronClassType.getEu_jr()};
        super.update(sql,paramsValue);
    }

    public void update(TronClasstype tronClassType ) {
        String sql = " UPDATE eu_tronclass SET year = ?,tron_month =?,eu_rj =?," +
                "eu_xin =?,eu_rw=?,eu_ts=?,eu_xiu=?,eu_gz=?,eu_kuai=?," +
                "eu_ad=?,eu_wc=?,eu_wu=?,eu_jr=? where id=?";
        Object[] paramsValue = {tronClassType.getYear(),tronClassType.getTron_month(),
                tronClassType.getEu_rj(),   tronClassType.getEu_xin(),
                tronClassType.getEu_rw(),   tronClassType.getEu_ts(),
                tronClassType.getEu_xiu(),  tronClassType.getEu_gz(),
                tronClassType.getEu_kuai(), tronClassType.getEu_ad(),
                tronClassType.getEu_wc(),   tronClassType.getEu_wu(),
                tronClassType.getEu_jr(),   tronClassType.getId()};
        super.update(sql,paramsValue);
    }
    public void delete(int id) {
        String sql = " delete from eu_tronclass where id =? ";
        Object[] paramsValue = {id};
        super.update(sql,paramsValue);
    }
}

文章文集:JavaEE--學(xué)習(xí)筆記

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容