`
jetway
  • 浏览: 483762 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

泛型dao

    博客分类:
  • java
阅读更多

1.

package yezhong.net.dao;

public abstract interface BaseDao<T> extends GenericDao<T, Long>{
}

 

 

2. 

 package yezhong.net.dao;

import be.common.tools.util.pagnation.Pagenation;
import com.htsoft.core.command.QueryFilter;
import com.htsoft.core.web.paging.PagingBean;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

public abstract interface GenericDao<T, PK extends Serializable>
{
  public abstract T save(T paramT);

  public abstract T merge(T paramT);

  public abstract T get(PK paramPK);

  public abstract void remove(PK paramPK);

  public abstract void remove(T paramT);

  public abstract void evict(T paramT);

  public abstract List<T> getAll();

  public abstract List<T> getAll(PagingBean paramPagingBean);

  public abstract List<T> getAll(QueryFilter paramQueryFilter);

  public abstract List<T> findByHql(String paramString, Object[] paramArrayOfObject);

  public abstract List<T> findByHql(String paramString, Object[] paramArrayOfObject, PagingBean paramPagingBean);

  public abstract List<T> findByHql(String paramString, Object[] paramArrayOfObject, int paramInt1, int paramInt2);

  public abstract void delByState(PK paramPK);

  public abstract List<T> getListBySql(String paramString);

  public abstract List<T> getListBySql(String paramString, Map<String, String> paramMap);

  public abstract Object getObjectBySql(String paramString);

  public abstract Object getObjectBySql(String paramString, Map<String, String> paramMap);

  public abstract List getPageBySql(String paramString, Pagenation paramPagenation);

  public abstract List getAllByHql(QueryFilter paramQueryFilter, List paramList, String paramString);
}

 

 

 3.

package yezhong.net..dao.impl;

import com.htsoft.core.dao.BaseDao;

public class BaseDaoImpl<T> extends GenericDaoImpl<T, Long>
  implements BaseDao<T>
{
  public BaseDaoImpl(Class persistType)
  {
    super(persistType);
  }
}

 

4.

 

package yezhong.net.dao.impl;

import be.common.tools.util.pagnation.Pagenation;
import com.htsoft.core.command.CriteriaCommand;
import com.htsoft.core.command.FieldCommandImpl;
import com.htsoft.core.command.QueryFilter;
import com.htsoft.core.command.SortCommandImpl;
import com.htsoft.core.dao.GenericDao;
import com.htsoft.core.web.paging.PagingBean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.hql.ast.QueryTranslatorImpl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public abstract class GenericDaoImpl<T, PK extends Serializable> extends HibernateDaoSupport
  implements GenericDao<T, PK>
{
  protected JdbcTemplate jdbcTemplate;
  protected Class persistType;
  protected Map<String, String> querys = new HashMap();

  public void setJdbcTemplate(JdbcTemplate jdbcTemplate)
  {
    this.jdbcTemplate = jdbcTemplate;
  }

  public void setPersistType(Class persistType) {
    this.persistType = persistType;
  }

  public GenericDaoImpl(Class persistType) {
    this.persistType = persistType;
  }

  public T get(PK id)
  {
    return getHibernateTemplate().get(this.persistType, id);
  }

  public T save(T entity)
  {
    getHibernateTemplate().saveOrUpdate(entity);
    return entity;
  }

  public T merge(T entity)
  {
    getHibernateTemplate().merge(entity);
    return entity;
  }

  public void evict(T entity) {
    getHibernateTemplate().evict(entity);
  }

  public List find(String queryString, Object[] values, int firstResult, int pageSize)
  {
    return (List)getHibernateTemplate().execute(new HibernateCallback(queryString, values, pageSize, firstResult)
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Query queryObject = GenericDaoImpl.this.getSession().createQuery(this.val$queryString);
        if (this.val$values != null) {
          for (int i = 0; i < this.val$values.length; ++i) {
            queryObject.setParameter(i, this.val$values[i]);
          }
        }
        if (this.val$pageSize > 0) {
          queryObject.setFirstResult(this.val$firstResult).setMaxResults(
            this.val$pageSize).setFetchSize(this.val$pageSize);
        }
        return queryObject.list();
      }
    });
  }

  public List<T> getAll() {
    return (List)getHibernateTemplate().execute(new HibernateCallback()
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException
      {
        String hql = "from " + GenericDaoImpl.this.persistType.getName();
        Query query = session.createQuery(hql);
        return query.list();
      }
    });
  }

  public List<T> getAll(PagingBean pb)
  {
    String hql = "from " + this.persistType.getName();
    int totalItems = getTotalItems(hql, null).intValue();
    pb.setTotalItems(totalItems);
    return (List)getHibernateTemplate().execute(new HibernateCallback(hql, pb)
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Query query = session.createQuery(this.val$hql);
        query.setFirstResult(this.val$pb.getFirstResult()).setFetchSize(this.val$pb.getPageSize().intValue());
        query.setMaxResults(this.val$pb.getPageSize().intValue());
        return query.list();
      }
    });
  }

  public Long getTotalItems(String queryString, Object[] values)
  {
    QueryTranslatorImpl queryTranslator = new QueryTranslatorImpl(queryString, queryString,
      Collections.EMPTY_MAP, (SessionFactoryImplementor)getSessionFactory());
    queryTranslator.compile(Collections.EMPTY_MAP, false);
    String sql = "select count(*) from (" + queryTranslator.getSQLString() + ") tmp_count_t";

    BigDecimal reVal = (BigDecimal)getHibernateTemplate().execute(new HibernateCallback(sql, values)
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        SQLQuery query = session.createSQLQuery(this.val$sql);
        if (this.val$values != null) {
          for (int i = 0; i < this.val$values.length; ++i) {
            query.setParameter(i, this.val$values[i]);
          }
        }
        return query.uniqueResult();
      }
    });
    return Long.valueOf(reVal.longValue());
  }

  public List<T> findByHql(String hql, Object[] objs)
  {
    return (List)getHibernateTemplate().execute(new HibernateCallback(hql, objs)
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Query query = session.createQuery(this.val$hql);
        if (this.val$objs != null) {
          for (int i = 0; i < this.val$objs.length; ++i) {
            query.setParameter(i, this.val$objs[i]);
          }
        }
        return query.list();
      }
    });
  }

  public List<T> findByHql(String hql, Object[] objs, int firstResult, int pageSize) {
    return (List)getHibernateTemplate().execute(new HibernateCallback(hql, firstResult, pageSize, objs)
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Query query = session.createQuery(this.val$hql);
        query.setFirstResult(this.val$firstResult).setMaxResults(this.val$pageSize);
        if (this.val$objs != null) {
          for (int i = 0; i < this.val$objs.length; ++i) {
            query.setParameter(i, this.val$objs[i]);
          }
        }
        return query.list();
      }
    });
  }

  public List<T> findByHql(String hql, Object[] objs, PagingBean pb) {
    int totalItems = getTotalItems(hql, objs).intValue();
    pb.setTotalItems(totalItems);
    return findByHql(hql, objs, pb.getFirstResult(), pb.getPageSize().intValue());
  }

  public List<T> findByHql(String hql) {
    return findByHql(hql, null);
  }

  public void remove(PK id) {
    getHibernateTemplate().delete(get(id));
  }

  public void remove(T entity) {
    getHibernateTemplate().delete(entity);
  }

  public Object findUnique(String hql, Object[] values)
  {
    return getHibernateTemplate().execute(new HibernateCallback(hql, values)
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Query query = session.createQuery(this.val$hql);

        if (this.val$values != null) {
          for (int i = 0; i < this.val$values.length; ++i) {
            query.setParameter(i, this.val$values[i]);
          }
        }
        return query.uniqueResult();
      }
    });
  }

  public int getCountByFilter(QueryFilter filter)
  {
    Integer count = (Integer)getHibernateTemplate().execute(new HibernateCallback(filter)
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Criteria criteria = session.createCriteria(GenericDaoImpl.this.persistType);
        for (int i = 0; i < this.val$filter.getCommands().size(); ++i) {
          CriteriaCommand command = (CriteriaCommand)this.val$filter.getCommands().get(i);
          if (!command instanceof SortCommandImpl) {
            criteria = command.execute(criteria);
          }
        }
        criteria.setProjection(Projections.rowCount());
        return criteria.uniqueResult();
      }
    });
    if (count == null) count = new Integer(0);
    return count.intValue();
  }

  public List getAll(QueryFilter queryFilter)
  {
    if (StringUtils.isNotEmpty(queryFilter.getFilterName())) {
      return getAll2(queryFilter, new ArrayList());
    }

    int totalCounts = getCountByFilter(queryFilter);

    queryFilter.getPagingBean().setTotalItems(totalCounts);

    List resultList = (List)getHibernateTemplate().execute(new HibernateCallback(queryFilter) {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Criteria criteria = session.createCriteria(GenericDaoImpl.this.persistType);

        this.val$queryFilter.getAliasSet().clear();
        GenericDaoImpl.this.setCriteriaByQueryFilter(criteria, this.val$queryFilter);
        return criteria.list();
      }
    });
    return resultList;
  }

  public List getAll2(QueryFilter queryFilter, List list)
  {
    String hql = ((String)this.querys.get(queryFilter.getFilterName())).trim();
    return getAllByHql(queryFilter, list, hql);
  }

  private Criteria setCriteriaByQueryFilter(Criteria criteria, QueryFilter filter)
  {
    for (int i = 0; i < filter.getCommands().size(); ++i) {
      criteria = ((CriteriaCommand)filter.getCommands().get(i)).execute(criteria);
    }

    criteria.setFirstResult(filter.getPagingBean().getFirstResult());
    criteria.setMaxResults(filter.getPagingBean().getPageSize().intValue());

    return criteria;
  }

  public void setQuerys(Map<String, String> querys)
  {
    this.querys = querys;
  }

  public void delByState(PK id)
  {
    try {
      Object t = this.persistType.newInstance();
      Class.forName(this.persistType.getName());

      getHibernateTemplate().update(null);
    }
    catch (InstantiationException e) {
      e.printStackTrace();
    }
    catch (IllegalAccessException e) {
      e.printStackTrace();
    }
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }

  public List getPageBySql(String sqlName, Pagenation params)
  {
    return (List)getHibernateTemplate().execute(new HibernateCallback(sqlName, params)
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Query sqlQuery = session.getNamedQuery(this.val$sqlName);
        if (this.val$params != null) {
          Map parMap = this.val$params.getParams();
          int size = parMap.size();
          if (size != 0) {
            Iterator iterator = parMap.keySet().iterator();
            for (int i = 0; i < size; ++i) {
              Object key = iterator.next();
              sqlQuery.setString(String.valueOf(key), String.valueOf(parMap.get(key)));
            }
          }
        }

        sqlQuery.setFirstResult(this.val$params.getStart())
          .setMaxResults(this.val$params.getLimit())
          .setFetchSize(this.val$params.getLimit());

        return sqlQuery.list();
      }
    });
  }

  public List getListBySql(String sqlName)
  {
    return getListBySql(sqlName, null);
  }

  public List getListBySql(String sqlName, Map<String, String> params)
  {
    return (List)getHibernateTemplate().execute(new HibernateCallback(sqlName, params)
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Query sqlQuery = session.getNamedQuery(this.val$sqlName);
        if ((this.val$params != null) &&
          (this.val$params.size() != 0)) {
          Iterator iterator = this.val$params.keySet().iterator();
          for (int i = 0; i < this.val$params.size(); ++i) {
            String key = iterator.next().toString().trim();
            sqlQuery.setString(key, (String)this.val$params.get(key));
          }
        }

        return sqlQuery.list();
      }
    });
  }

  public Object getObjectBySql(String sqlName)
  {
    return getObjectBySql(sqlName, null);
  }

  public Object getObjectBySql(String sqlName, Map<String, String> params)
  {
    return getHibernateTemplate().execute(new HibernateCallback(sqlName, params)
    {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Query sqlQuery = session.getNamedQuery(this.val$sqlName);
        if ((this.val$params != null) &&
          (this.val$params.size() != 0)) {
          Iterator iterator = this.val$params.keySet().iterator();
          for (int i = 0; i < this.val$params.size(); ++i) {
            String key = iterator.next().toString().trim();
            sqlQuery.setString(key, (String)this.val$params.get(key));
          }
        }

        return sqlQuery.uniqueResult();
      }
    });
  }

  public List getAllByHql(QueryFilter queryFilter, List list, String hql)
  {
    String newHql = null;
    String condition = null;

    int orderIndex = hql.toUpperCase().indexOf(" ORDER BY ");
    int whereIndex = hql.toUpperCase().indexOf(" WHERE ");

    if (orderIndex < 0) {
      orderIndex = hql.length();
    }
    if (whereIndex < 0) {
      whereIndex = hql.length();
    }

    if (whereIndex < 0) {
      condition = " where 1=1 ";
    } else {
      condition = hql.substring(whereIndex + 7, orderIndex);
      condition = " where (" + condition + ")";
    }
    String sortDesc = "";

    for (int i = 0; i < queryFilter.getCommands().size(); ++i) {
      CriteriaCommand command = (CriteriaCommand)queryFilter.getCommands().get(i);
      if (command instanceof FieldCommandImpl) {
        condition = condition + " and " + ((FieldCommandImpl)command).getPartHql();
      } else if (command instanceof SortCommandImpl) {
        if (!"".equals(sortDesc)) {
          sortDesc = sortDesc + ",";
        }
        sortDesc = sortDesc + ((SortCommandImpl)command).getPartHql();
      }
    }

    newHql = hql.substring(0, whereIndex);

    if (queryFilter.getAliasSet().size() > 0)
    {
      int fromIndex = newHql.toUpperCase().indexOf(" FROM ");
      String entityAliasName = null;
      if (fromIndex > 0) {
        String afterFrom = newHql.substring(fromIndex + 6);

        String[] keys = afterFrom.split("[ ]");
        if ((keys.length > 1) &&
          (!keys[1].toUpperCase().equals("ORDER")) &&
          (!keys[1].toUpperCase().equals("JOIN"))) {
          entityAliasName = keys[1];
        }

        if (entityAliasName == null) {
          entityAliasName = "vo";
          newHql = newHql.replace(keys[0], keys[0] + " " + entityAliasName);
        }

      }

      String joinHql = "";
      Iterator it = queryFilter.getAliasSet().iterator();
      while (it.hasNext()) {
        String joinVo = (String)it.next();
        joinHql = joinHql + " join " + entityAliasName + "." + joinVo + " " + joinVo;
      }

      if (!"".equals(joinHql)) {
        newHql = newHql + joinHql;
      }
    }

    newHql = newHql + condition;

    if (!"".equals(sortDesc))
      newHql = newHql + " order by " + sortDesc;
    else {
      newHql = newHql + hql.substring(orderIndex);
    }
    list.addAll(queryFilter.getParamValueList());
    Object[] params = list.toArray();

    int totalItems = getTotalItems(newHql, params).intValue();
    queryFilter.getPagingBean().setTotalItems(totalItems);

    return find(newHql, params, queryFilter.getPagingBean().getFirstResult(), queryFilter.getPagingBean().getPageSize().intValue());
  }
}

分享到:
评论

相关推荐

    泛型dao 泛型dao 泛型dao

    Struts2、Hibernate、Spring整合的泛型DAO (本人评价: 代码开发效率提高30% 代码出错率减少70%) 对于大多数开发人员,系统中的每个 DAO 编写几乎相同的代码到目前为止已经成为一种习惯。虽然所有人都将这种重复...

    经典泛型dao层代码,非常好用简易

    ### 泛型DAO层在SSH框架中的应用与详解 #### 引言 在现代软件开发中,特别是基于Java的企业级应用开发中,DAO(Data Access Object)层的设计扮演着至关重要的角色。它作为业务逻辑层与数据持久层之间的桥梁,承担...

    一个很好的通用泛型dao(含源码)

    而泛型DAO是一个类型安全的,代码精简的设计模式(相对于传统DAO),尤其在DAO组件数量庞大的时候,代码量的减少更加明显。 泛型DAO的核心是定义一个GenericDao接口,声明基本的CRUD操作: 用hibernate作为持久化...

    Hibernate泛型DAO(结合spring模板支持)

    至于`Dao经典泛型.doc`文件,可能是更深入的关于Hibernate泛型DAO的文档,可能包含了如何配置Spring、如何处理复杂查询以及如何优化泛型DAO的更多细节。阅读这份文档将进一步提升你对泛型DAO的理解和应用能力。 ...

    Hibernate泛型Dao

    【标题】"Hibernate泛型Dao"是针对Java开发中的数据持久化框架Hibernate的一个高级应用,主要目的是为了提高代码的复用性和简洁性。在传统的Hibernate使用中,针对每个实体类,我们都需要创建一个对应的Dao(Data ...

    JdbcTemplate通用泛型Dao实现

    本文将深入探讨`JdbcTemplate`通用泛型Dao实现的相关知识点,帮助开发者更好地理解和应用这一技术。 首先,让我们了解什么是`JdbcTemplate`。它是Spring框架的一部分,用于处理SQL操作。`JdbcTemplate`提供了一组...

    大家看看我设计的泛型DAO(使用Spring的Anotation和Hibernate)

    本篇文章将深入探讨一个使用Spring注解和Hibernate实现的泛型DAO设计,以提高代码的复用性和可维护性。 首先,`HibernateBaseDao.java`是基础的Hibernate DAO类,它提供了对Hibernate操作的基本封装。这个类通常会...

    S2SH整合例子 注解配置 JSON 泛型Dao

    6. **泛型Dao**:在Java开发中,泛型Dao(Generic Dao)是一种设计模式,用于减少重复的数据库操作代码。通过定义一个通用的Dao接口,可以实现对不同类型的实体对象进行CRUD操作,提高了代码的复用性和可维护性。...

    泛型DAO模式在Java Web开发中的应用.pdf

    泛型DAO模式在Java Web开发中的应用 摘要: 泛型DAO模式是Java Web开发中的一种重要模式,它可以提高数据访问代码的类型安全性和可读性。该模式可以与Struts、Spring和JPA框架集成,实现用户管理系统的开发。通过...

    泛型DAO,注释详细

    泛型DAO(Generic DAO)是DAO模式的一个扩展,它引入了泛型的概念,提高了代码的复用性和类型安全性。本篇文章将深入探讨泛型DAO的实现原理、优势以及如何在实际项目中应用。 首先,我们来理解什么是泛型。泛型是...

    Java Web程序运用中泛型DAO的作用.pdf

    本文探讨了在Java Web程序中应用泛型DAO模式的作用和意义。首先,文章明确了Java Web技术的定义和在互联网领域中的重要性,阐述了随着软件功能需求的不断提高,Java Web技术也在不断升级和改造。随后,文章指出泛型...

    spring hibernate 泛型DAO

    本文将深入探讨“Spring Hibernate 泛型DAO”这一主题,以及如何通过泛型DAO实现更加高效、可复用的代码。 首先,让我们理解什么是DAO(Data Access Object)模式。DAO是一种设计模式,它的主要作用是隔离业务逻辑...

    Hibernate泛型DAO及使用方法.doc

    而泛型DAO(Data Access Object)则是基于Hibernate进一步抽象出来的一个设计模式,用于提供更通用的数据操作方法。本文档主要探讨了如何在Spring+Hibernate环境中创建和使用泛型DAO。 首先,我们来看一下泛型DAO...

    Java Web程序运用中泛型DAO的作用.zip

    而泛型DAO是DAO模式的一个进阶应用,它通过引入泛型来提高代码的复用性和可维护性。 泛型(Generics)是Java 5引入的一个重要特性,它可以让我们在编译时检查类型安全,并且允许我们创建参数化的类型。在泛型DAO中...

    SSH 泛型DAO分页

    这个压缩包文件的标题"SSH 泛型DAO分页"表明它提供了一个实现SSH框架整合的示例,特别关注了泛型DAO(Data Access Object)以及分页功能。下面将详细介绍SSH框架及其分页和泛型DAO的概念。 1. **Struts2**: Struts2...

    基于hibernate的泛型Dao框架

    标题中的“基于Hibernate的泛型Dao框架”是指在Java开发中使用Hibernate ORM工具,并结合泛型设计模式构建的数据库访问对象(DAO)框架。这样的框架旨在提高代码复用性,减少重复工作,使得数据访问层的实现更加简洁...

    ssh通用泛型DAO

    在这个主题中,我们将深入探讨"ssh通用泛型DAO"的相关知识点。 首先,我们来了解"BaseHibernateDAO"。BaseHibernateDAO是基于Hibernate框架的一个基类,它封装了常见的数据库操作,如增删查改(CRUD)。通过继承这...

Global site tag (gtag.js) - Google Analytics