一个很优美的操作dao的接口设计方案

通常在业务代码里面会进行dao的操作,dao层会提供正删改查等api,如何减少重复的增删改查,使得代码更简洁

 有图为证:

一个很优美的操作dao的接口设计方案_第1张图片

1.首先说明IBaseDAO,这个接口主要是定义一些常用的增删改查方法

package com.bj58.xxzl.hunter.configure.web.dao;

import com.bj58.xxzl.hunter.configure.web.dao.entity.Field;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;


public interface IBaseDAO {

    /**
     * 获取实体
     * @param id
     * @return
     * @throws Exception
     */
    public T get(PK id) throws Exception;
    /**
     * 更新实体
     * @param entity
     * @throws Exception
     */
    public void update(T entity) throws Exception;
    /**
     * 获取实体List
     * @param arr
     * @return
     * @throws Exception
     */
    public List getList(PK[] arr) throws Exception;
    /**
     * 向数据库中增加实体
     * @param entity
     * @return TODO
     * @throws Exception
     */
    public PK save(T entity) throws Exception;
    /**
     * 根据主键删除数据库实体
     * @param id
     * @throws Exception
     */
    public void delete(PK id) throws Exception;
    /**
     * 计算总量
     * @param condition
     * @return
     * @throws Exception
     */
    public int count(String condition) throws Exception;
    /**
     * 按条件分页查询
     * @param condition
     * @param columns
     * @param page
     * @param pageSize
     * @param orderBy
     * @return
     * @throws Exception
     */
    public List getListByPage(String condition, String columns, int page,
                                 int pageSize, String orderBy) throws Exception;

    /**
     * 按照条件分页查询
     * @param condition
     * @param page
     * @param pageSize
     * @param orderColum
     * @param isAsc
     * @return
     */
    public List getListByPage(String condition, int page,
                                 int pageSize, String orderColum, boolean isAsc) throws Exception;
    /**
     * 加载全部数据(仅在数据量比较小的情况下使用)
     * @param condition
     * @return
     * @throws Exception
     */
    public List loadAll(String condition) throws Exception;


    /**
     * 加载全部数据(仅在数据量比较小的情况下使用)
     * @return
     * @throws Exception
     */
    public List loadAll() throws Exception;

    /**
     * 根据主键ID批量上删除
     * @param ids
     * @throws Exception
     */
    public void deleteBatch(List ids) throws Exception;

    /**
     * 批量更新
     * @param collection
     * @throws Exception
     */
    public void updateBatch(Collection collection) throws Exception;

    /**
     * 批量保存
     * @param collection
     * @throws Exception
     */
    public void saveBatch(Collection collection) throws Exception;

    public void saveBatchTx(Collection collection, Field field) throws Exception;


    /**
     * 执行SQL(search)
     * @param sql
     * @throws Exception
     */
    public List executeSql(String sql) throws Exception;

    /**
     * 执行sql(update or insert)
     * @param sql
     * @return
     * @throws Exception
     */
    public int executeSqlForUpdate(String sql) throws Exception;

    /**
     * 根据SQL查询
     * @param sql
     * @param param
     * @return
     * @throws Exception
     */
    public List getListBySQL(String sql, Object... param) throws Exception;

    /**
     * 根据ID列表批量删除
     * @param ids
     * @throws Exception
     */
    public void deleteBatch(Integer[] ids) throws Exception;

    /**
     * 执行sql
     * @param sql
     * @param params
     * @return
     * @throws Exception
     */
    public int execBySQL(String sql,Object... params) throws Exception;

    /**
     * 根据SQL查询数量
     * @param sql
     * @param param
     * @return
     * @throws Exception
     */
    public int count(String sql, Object... param) throws Exception;

    /**
     * 根据SQL查询数据
     * @param aclass
     * @param sql
     * @param param
     * @return
     * @throws Exception
     */
    public List getListBySQL(Class aclass, String sql, Object... param) throws Exception;

    /**
     * 分页加载全部数据
     *
     * @param condition
     * @return
     * @throws Exception
     */
    public List loadAllByPage(String condition) throws Exception;
}

2.然后是定义BaseDAOImpl,这个类继承IBaseDAOImpl,对一些常用的api进行实现,同时定义数据库操作的daohelper,以后的各种数据库表的操作都需要继承这个类,主要是将数据库常用的操作都继承过来,这个类上面有泛型T和PK,T为返回的结果类型,PK为入参

import com.alibaba.fastjson.JSON;
import com.bj58.sfft.utility.dao.basedao.DAOHelper;
import com.bj58.xxzl.hunter.configure.web.controllers.FieldSceneController;
import com.bj58.xxzl.hunter.configure.web.dao.IBaseDAO;
import com.bj58.xxzl.hunter.configure.web.dao.entity.Field;
import com.bj58.xxzl.hunter.configure.web.dao.support.DAOHelperSupport;
import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.util.Collection;
import java.util.List;
import java.util.Map;


public class BaseDAOImpl implements IBaseDAO {
    private static final Log logger = LogFactory.getLog(BaseDAOImpl.class);

    protected  DAOHelper da= DAOHelperSupport.getDaoHelper();
    protected final Class aclass;

    @SuppressWarnings("unchecked")
    public BaseDAOImpl(){
        this.aclass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Override
    @SuppressWarnings("unchecked")
    public T get(PK id) throws Exception {
        return (T) da.sql.get(aclass, id);
    }

    @Override
    public void update(T entity) throws Exception {
        da.sql.upateEntity(entity);
    }

    @Override
    public List getList(PK[] arr) throws Exception {
        return da.sql.getListByIDS(aclass,arr);
    }

    @SuppressWarnings("unchecked")
    @Override
    public PK save(T entity) throws Exception {
        return (PK) da.sql.insert(entity);
    }

    @Override
    public void delete(PK id) throws Exception {
        da.sql.deleteByID(aclass, id);
    }

    @Override
    public int count(String condition) throws Exception {
        return da.sql.getCount(aclass, condition);
    }

    @Override
    public int count(String sql, Object... param) throws Exception {
        return da.sql.getCountBySQL(sql, param);
    }

    @Override
    public List getListBySQL(Class aclass, String sql, Object... param) throws Exception {
        return da.sql.getListBySQL(aclass, sql, param);
    }

    @Override
    public List loadAllByPage(String condition) throws Exception {
        int count = count(condition);
        int pageSize = 500;
        if(count <= pageSize) {
            return loadAll(condition);
        }
        int page = (count-1)/pageSize+1;
        int startPage = 1;
        List list = Lists.newArrayListWithExpectedSize(count);
        while( startPage <= page ) {
            List entityList = getListByPage(condition, "*", startPage, pageSize, "id");
            list.addAll(entityList);
            startPage++;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("loadAllByPage(" + condition + ") ret=" + list);
        }
        return list;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List getListByPage(String condition, String columns, int page,
                                 int pageSize, String orderBy) throws Exception {
        return da.sql.getListByPage(aclass, condition, columns, page, pageSize, orderBy);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List getListByPage(String condition, int page, int pageSize,
                                 String orderColum, boolean isAsc) throws Exception{
        String orderby  = orderColum  + (isAsc?" asc":" desc");
        return da.sql.getListByPage(aclass, condition, "*", page, pageSize, orderby);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List loadAll(String condition) throws Exception{
        return da.sql.getListByCustom(aclass, "*", condition, "");
    }

    @Override
    @SuppressWarnings("unchecked")
    public List loadAll() throws Exception{
        return da.sql.getListByCustom(aclass, "*", "", "");
    }

    @Override
    public void deleteBatch(List ids) throws Exception {
        if (ids != null) {
            for (PK pk : ids) {
                da.sql.deleteByID(aclass, pk);
            }
        }
    }

    @Override
    public void deleteBatch(Integer[] ids) throws Exception {
        da.sql.deleteByIDS(aclass,ids);
    }

    @Override
    public void updateBatch(Collection collection) throws Exception {
        for(T t: collection){
            da.sql.upateEntity(t);
        }
    }

    @Override
    public void saveBatch(Collection collection) throws Exception {
        for(T t: collection){
            da.sql.insert(t);
        }
    }

    /**
     * 支持事务的更新
     * @param collection
     * @param field
     * @throws Exception
     */
    @Override
    public void saveBatchTx(Collection collection, Field field) throws Exception {
        logger.info("collection = " + JSON.toJSONString(collection) + " field = " + JSON.toJSONString(field));
        try {
            da.beginTransaction(Connection.TRANSACTION_REPEATABLE_READ);
            da.sql.upateEntity(field);

            for(T t: collection){
                da.sql.insert(t);
            }
            da.commitTransaction();
        }catch (Throwable e){
            try {
                logger.error("tx  error ",e);
                da.rollbackTransaction();
                logger.error("事务进行回滚");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    public DAOHelper getDa() {
        return da;
    }

    public void setDa(DAOHelper da) {
        this.da = da;
    }

    @Override
    public List executeSql(String sql) throws Exception {
        return da.sql.getListBySQL(aclass, sql);
    }

    @Override
    public int executeSqlForUpdate(String sql) throws Exception {
        return da.sql.execBySQL(sql);
    }

    @Override
    public int execBySQL(String sql,Object... params) throws Exception {
        return da.sql.execBySQL(sql, params);
    }

    @Override
    public List getListBySQL(String sql, Object... param) throws Exception {
        return da.sql.getListBySQL(aclass, sql, param);
    }

}

3.然后是定义IStrategyDAO,这个接口主要是继承了IBaseDAO,将一些基础的数据库操作接口继承过来,同时可以定义一些Strategy类自有的特殊的方法定义

import com.bj58.xxzl.hunter.configure.web.dao.entity.Strategy;
import com.bj58.xxzl.hunter.configure.web.utils.Page;

import java.util.List;
import java.util.Map;


public interface IStrategyDAO extends IBaseDAO {


    public List getByRuleId(int ruleId)throws Exception;

    public List getByToolId(int toolId) throws Exception;


    /**
     * 根据搜索条件搜索策略
     * @param searchMap 搜索条件map
     * @param pageNo 页码
     * @param pageSize 页面大小
     * @return
     * @throws Exception
     */
    public Page search(Map searchMap,int pageNo,int pageSize)throws Exception;


    /**
     * 根据策略名获取策略
     * @param strategyName
     * @return
     * @throws Exception
     */
    public Strategy getByName(String strategyName)throws Exception;

    /**
     * 获取预上线的数目
     * @return
     * @throws Exception
     */
    public int getPreOnlineCount()throws Exception;


}
4.最后就是我们的StrateDAOImpl,它继承了BaseDAOImpl,获取了所有的基础的数据库操作,同时实现了IStrateDAOImpl,获取了Strategy类的接口定义,然后实现这些自有的方法
import java.util.*;


public class StrategyDAOImpl extends BaseDAOImpl implements IStrategyDAO {

    private static final Log log = LogFactory.getLog(StrategyDAOImpl.class);


    //IStrategyDAO 接口定义的方法的实现

}

5.后面所有表的操作只需要定义对应的接口,然后继承实现IBaseDAO和BaseDAOIml就可以了,然后分别有各自的实现

你可能感兴趣的:(解决方案)