论坛首页 入门技术论坛

DAO问题讨论的<结束>

浏览 1447 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-09-02  
DAO
上编是关于DAO的讨论问题,通过这个一个讨论在这一过程当中我们每一人持的不同的看法,我想的是不管怎么样的DAO分层与整合的设计,都要依据我们的软件项目来衡量,从软件的角度上来看,就是要开发一个很完美的,效率高,运行很稳定的软件,为我们的每一个客户服务,因为客户关心的是他们的数据与数据的安全,而不是在于你们使用的怎么的代码逻辑设计思想,今天我就来做一个DAO的全面的总结吧,首先通过一个JDBC首先的一个DAO整合方法,在这个DAO的整合方法中,把我们经常定义的小类DAO方法收样到大的DAO整合方法中来,进行他们的执行操作,包含对数据库的SQL的执行控制(指的SQL的执行次数,SQL每秒执行规定的数据量)能实现到这样的,能大大的减少我们的数据库的频繁执行SQL的操作,在这样大DAO方法包含了 数据的增加,删除,更新,修改在每个小DAO的方法中主要直接转进参数进来,大的DAO法执行了在把结果集给小DAO,这里说明,不是Service层,而是DAO,上一编中 有人讲是Serviece层,我在这里说不是它,而是DAO层。假如我们以后的业务修改了,我们的DAO就没有进行大刀的修改与操作,主要关心我们的业务控制逻辑层就是了。竟然我们的DAO可以这样写,那么我们的Service层可以这样写,不过要根据自己的软件要求。就这搁笔吧,请看代码如下:

<!!!-----------DAO--->
public abstract class BaseHibernateDao extends HibernateDaoSupport
{

    public BaseHibernateDao()
    {
    }

    protected abstract Class getEntityClass();

    public Object get(Serializable id)
    {
        Object o = getHibernateTemplate().get(getEntityClass(), id);
        if(o == null)
            throw new ObjectRetrievalFailureException(getEntityClass(), id);
        else
            return o;
    }

    public List getAll()
    {
        return getHibernateTemplate().loadAll(getEntityClass());
    }

    public void removeByHql(String hql)
    {
        Query q = getSession().createQuery(hql);
        q.executeUpdate();
    }

    public void save(Object o)
    {
        getHibernateTemplate().save(o);
    }

    public void update(Object o)
    {
        getHibernateTemplate().update(o);
    }

    public void remove(Serializable id)
    {
        remove(get(id));
    }

    public void remove(int id)
    {
        remove(get(new Integer(id)));
    }

    public void remove(Object o)
    {
        getHibernateTemplate().delete(o);
    }

    public List find(String hsql)
    {
        return getHibernateTemplate().find(hsql);
    }

    public List find(String hsql, Object value)
    {
        return getHibernateTemplate().find(hsql, value);
    }

    public List find(String hsql, Object values[])
    {
        return getHibernateTemplate().find(hsql, values);
    }

    public Object findBy(String name, Object value)
    {
        Criteria criteria = getSession().createCriteria(getEntityClass());
        criteria.add(Restrictions.eq(name, value));
        return criteria.uniqueResult();
    }

    public List findAllBy(String name, Object value)
    {
        Criteria criteria = getSession().createCriteria(getEntityClass());
        criteria.add(Restrictions.eq(name, value));
        return criteria.list();
    }

    public List findAllByLike(String name, Object value)
    {
        Criteria criteria = getSession().createCriteria(getEntityClass());
        criteria.add(Restrictions.like(name, value));
        return criteria.list();
    }

    public List findAllBy(Map filter)
    {
        Criteria criteria = getSession().createCriteria(getEntityClass());
        filterCriteria(criteria, filter);
        return criteria.list();
    }

    public Page pagedQuery(String hql, int pageNo, int pageSize)
    {
        return pagedQuery(hql, null, pageNo, pageSize);
    }

    public Page pagedQuery(String hql, Object args[], int pageNo, int pageSize)
    {
        int end = hql.indexOf("order");
        end = end != -1 ? end : hql.length();
        String sql = (new StringBuilder()).append("select count(*) as total ").append(hql.substring(hql.indexOf("from"), end)).toString();
        int total = 0;
        try
        {
            List l = getHibernateTemplate().find(sql, args);
            total = ((Integer)l.get(0)).intValue();
        }
        catch(Exception ex)
        {
            logger.error(ex);
        }
        return pagedQuery(hql, args, pageNo, pageSize, total);
    }

    public Page pagedQuery(String hql, Object args[], int pageNo, int pageSize, int total)
    {
        if(hql == null)
            throw new IllegalArgumentException("NULL is not a valid HQL string");
        Query query = getSession().createQuery(hql);
        if(args != null)
        {
            for(int i = 0; i < args.length; i++)
                query.setParameter(i, args[i]);

        }
        return HqlPage.getHibernatePageInstance(query, pageNo, pageSize, total);
    }

    public List findAllBy(Map filter, Map sortMap, int rowStart, int rowDisplayed)
    {
        Criteria criteria = getSession().createCriteria(getEntityClass());
        filterCriteria(criteria, filter);
        sortCriteria(criteria, sortMap);
        criteria.setProjection(null);
        criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
        criteria.setFirstResult(rowStart);
        criteria.setMaxResults(rowDisplayed);
        return criteria.list();
    }

    protected void filterCriteria(Criteria criteria1, Map map)
    {
    }

    private void sortCriteria(Criteria criteria, Map sortMap)
    {
        if(!sortMap.isEmpty())
        {
            for(Iterator iterator = sortMap.keySet().iterator(); iterator.hasNext();)
            {
                String fieldName = iterator.next().toString();
                String orderType = sortMap.get(fieldName).toString();
                if("asc".equalsIgnoreCase(orderType))
                    criteria.addOrder(Order.asc(fieldName));
                else
                    criteria.addOrder(Order.desc(fieldName));
            }

        }
    }

    public int getCount(Map filter)
    {
        Criteria criteria = getSession().createCriteria(getEntityClass());
        filterCriteria(criteria, filter);
        Integer count = (Integer)criteria.setProjection(Projections.rowCount()).uniqueResult();
        return count.intValue();
    }

    protected final Log logger = LogFactory.getLog(getClass());
}

<!---DaoSupport---->

public class BaseHibernateSuport extends HibernateDaoSupport
{

    public BaseHibernateSuport()
    {
    }

    public int getCount(String hsql, Object obj[])
        throws HibernateException, SQLException
    {
        int total = 0;
        try
        {
            List l = getHibernateTemplate().find(hsql, obj);
            total = ((Integer)l.get(0)).intValue();
        }
        catch(Exception ex)
        {
            logger.error(ex);
        }
        return total;
    }

    public Vector swap(List list)
    {
        if(list != null)
        {
            Object obj = list.get(list.size() - 1);
            Vector ret = new Vector();
            ret.add(obj);
            list.remove(list.size() - 1);
            ret.addAll(list);
            return ret;
        } else
        {
            return null;
        }
    }
}

<!--DAO--->
public abstract class BaseDAO
{

    public BaseDAO()
    {
        conn = null;
        needClosed = null;
        isSharedCon = false;
        needClosed = new Vector();
        isSharedCon = false;
    }

    public Connection getCurrentConnection()
    {
        if(conn == null)
            conn = getConnection(CURRENTCONNECTIONSTYLE);
        return conn;
    }

    public Connection getConnection()
        throws SQLException
    {
        return getConnection(CURRENTCONNECTIONSTYLE);
    }

    public void setCurrentConnection(Connection conn)
        throws Exception
    {
        if(this.conn == null)
        {
            this.conn = conn;
        } else
        {
            closeConnection();
            this.conn = conn;
        }
    }

    public Connection getConnection(int style)
    {
        try
        {
            if(style == 0)
                conn = OaUtil.getConnection();
            else
            if(style == 1)
            {
                DriverManager.registerDriver(new OracleDriver());
                conn = DriverManager.getConnection((new StringBuilder()).append("jdbc:oracle:thin:@").append(hostname).append(":").append(port).append(":").append(dbSID).toString(), username, password);
            }
        }
        catch(Exception e)
        {
            System.out.println(e.toString());
            return null;
        }
        System.out.println("get database_connection successfully!");
        return conn;
    }

    public boolean begin()
        throws SQLException
    {
        if(isSharedCon)
            return true;
        if(conn == null)
            getCurrentConnection();
        conn.setAutoCommit(false);
        return true;
    }

    public boolean commit()
        throws SQLException
    {
        if(isSharedCon)
            return true;
        if(conn == null)
            getCurrentConnection();
        conn.commit();
        return true;
    }

    public boolean rollback()
        throws SQLException
    {
        if(isSharedCon)
            return true;
        if(conn == null)
            getCurrentConnection();
        conn.rollback();
        return true;
    }

    public ResultSet OpenSQL(String sql)
        throws SQLException
    {
        if(conn == null)
            getCurrentConnection();
        conn.setAutoCommit(true);
        Statement stmt = conn.createStatement(RESULTSETTYLE, RESULTSETCONCURRENCY);
        ResultSet rs = stmt.executeQuery(sql);
        needClosed.addElement(stmt);
        needClosed.addElement(rs);
        return rs;
    }

    public int executeSQL(String sql, boolean CommitAtOnce)
        throws SQLException
    {
        Statement stmt;
        int ret;
        stmt = null;
        ret = 0;
        if(conn == null)
            getCurrentConnection();
        if(CommitAtOnce)
            begin();
        stmt = conn.createStatement();
        ret = stmt.executeUpdate(sql);
        if(CommitAtOnce)
            commit();
        if(stmt != null)
            stmt.close();
        break MISSING_BLOCK_LABEL_106;
        Exception e;
        e;
        if(CommitAtOnce)
            rollback();
        if(stmt != null)
            stmt.close();
        break MISSING_BLOCK_LABEL_106;
        Exception exception;
        exception;
        if(stmt != null)
            stmt.close();
        throw exception;
        return ret;
    }

    public int executeSQL(String sql)
        throws SQLException
    {
        return executeSQL(sql, true);
    }

    public void closeConnection()
    {
        if(conn != null && !isSharedCon)
            try
            {
                for(int i = 0; i < needClosed.size(); i++)
                {
                    Object obj = needClosed.get(i);
                    if(obj instanceof Statement)
                    {
                        ((Statement)obj).close();
                        continue;
                    }
                    if(obj instanceof PreparedStatement)
                    {
                        ((PreparedStatement)obj).close();
                        continue;
                    }
                    if(obj instanceof ResultSet)
                        ((ResultSet)obj).close();
                }

                needClosed.clear();
                conn.close();
                conn = null;
            }
            catch(Exception e)
            {
                System.out.println((new StringBuilder()).append("baseDAO.closeConnection() exception:").append(e.toString()).toString());
            }
    }

    public abstract Object getFromRSCurRow(ResultSet resultset);

    public Vector getBeansFromResultSet(ResultSet rs)
    {
        Vector ret;
        ret = new Vector();
        for(; rs.next(); ret.addElement(getFromRSCurRow(rs)));
        return ret;
        Exception e;
        e;
        System.out.println((new StringBuilder()).append("BaseDAO.getBeansFromResultSet exception:").append(e.toString()).toString());
        return null;
    }

    public Vector getBeansFromResultSet(ResultSet rs, SearchInfo searchinfo)
    {
        if(!rs.next())
            return new Vector();
        Vector ret;
        int page;
        int row;
        int rowcount;
        ret = new Vector();
        page = searchinfo.getCurPage();
        if(page < 1)
            page = 1;
        row = (page - 1) * searchinfo.getPageSize() + 1;
        rowcount = 0;
        rowcount = 1;
_L1:
        if(rowcount >= row)
            break MISSING_BLOCK_LABEL_94;
        if(rs.next())
            break MISSING_BLOCK_LABEL_88;
        searchinfo.setCurPage(0);
        searchinfo.setRowsCount(rowcount);
        return ret;
        rowcount++;
          goto _L1
        int i = 0;
        i = 0;
        do
        {
            if(i >= searchinfo.getPageSize() && searchinfo.getPageSize() != 0)
                break;
            ret.addElement(getFromRSCurRow(rs));
            if(!rs.next())
                break;
            rowcount++;
            i++;
        } while(true);
        if(i != searchinfo.getPageSize())
            searchinfo.setPageSize(++i);
        searchinfo.setCurPage(page);
        while(rs.next())
            rowcount++;
        searchinfo.setRowsCount(rowcount);
        int tmpI = 0;
        if(rowcount == 0)
            tmpI = 0;
        else
        if(searchinfo.getPageSize() == 0)
        {
            tmpI = 1;
        } else
        {
            double tmpD = (double)rowcount / (double)searchinfo.getPageSize();
            tmpI = (int)tmpD;
            if(tmpD > (double)tmpI)
                tmpI++;
        }
        searchinfo.setPageCount(tmpI);
        return ret;
        Exception e;
        e;
        System.out.println((new StringBuilder()).append("BaseDAO.getBeansFromResultSet exception:").append(e.toString()).toString());
        return null;
    }

    public PreparedStatement createUpdateStatement(String sql)
    {
        PreparedStatement ret;
        if(conn == null)
            getCurrentConnection();
        ret = conn.prepareStatement(sql);
        needClosed.addElement(ret);
        return ret;
        Exception e;
        e;
        System.out.println((new StringBuilder()).append("BaseDAO.CreatePreparedStatement exception:").append(e.toString()).toString());
        return null;
    }

    public PreparedStatement createQueryStatement(String sql)
    {
        PreparedStatement ret;
        if(conn == null)
            getCurrentConnection();
        ret = conn.prepareStatement(sql);
        needClosed.addElement(ret);
        return ret;
        Exception e;
        e;
        System.out.println((new StringBuilder()).append("BaseDAO.CreatePreparedStatement exception:").append(e.toString()).toString());
        return null;
    }

    public ResultSet executeQuery(PreparedStatement prstms)
    {
        ResultSet rs;
        rs = prstms.executeQuery();
        needClosed.addElement(rs);
        return rs;
        Exception e;
        e;
        System.out.println((new StringBuilder()).append("BaseDAO. executeQuery exception:").append(e.toString()).toString());
        return null;
    }

    public int executeUpdate(PreparedStatement prstms)
    {
        int ret = prstms.executeUpdate();
        return ret;
        Exception e;
        e;
        System.out.println((new StringBuilder()).append("BaseDAO. executeupdate exception:").append(e.toString()).toString());
        return 0;
    }

    public Vector getNeedClosed()
    {
        return needClosed;
    }

    public void AddNeedClosed(Vector v)
    {
        needClosed.addAll(v);
    }

    public void ConnectTo(BaseDAO dao)
    {
        conn = dao.getCurrentConnection();
        needClosed = dao.getNeedClosed();
        isSharedCon = true;
    }

    public boolean getIsSharedConnection()
    {
        return isSharedCon;
    }


论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics