`
huiqinbo
  • 浏览: 344360 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
阅读更多

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());
  }
}

 

分享到:
评论
1 楼 xp55699312 2010-06-05  
反编译过来的吧。

相关推荐

    JdbcTemplate通用泛型Dao实现

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

    泛型dao 泛型dao 泛型dao

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

    spring-data-jdbc-repository, Spring Data JDBC泛型DAO实现.zip

    spring-data-jdbc-repository, Spring Data JDBC泛型DAO实现 Spring Data JDBC泛型DAO实现查看正在积极开发和维护的 jirutka/spring-data-jdbc-repository fork 。 不再支持这里存储库。本项目的目的是为基于 ...

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

    本文将深入探讨一种在SSH(Struts+Spring+Hibernate)框架中广泛应用的经典泛型DAO层实现方式,旨在展示其简洁性、高效性和灵活性。 #### 泛型DAO层:概念与优势 泛型DAO层通过利用Java的泛型机制,提供了一种类型...

    spring hibernate 泛型DAO

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

    Hibernate泛型Dao

    【描述】"基于hibernate5 泛型Dao实例,下载后改一下数据库配置直接可以用",意味着这个压缩包文件提供了一个已经实现好的Hibernate5版本的泛型Dao示例项目。用户只需要根据自己的数据库环境修改相应的配置信息,就...

    泛型dao

    在Java编程语言中,"泛型DAO"(Generic DAO)是一种设计模式,它允许开发者创建可重用的数据访问对象(DAOs),以处理多种不同类型的实体对象,而无需为每种对象编写单独的DAO实现。这种方法提高了代码的复用性和可...

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

    这种模式的核心在于利用Java的泛型特性,使得DAO方法可以处理任何类型的实体对象,而无需为每个实体类单独创建一个DAO实现。 首先,我们需要创建一个泛型DAO接口,如`GenericDao&lt;T&gt;`,其中`T`代表任意实体类类型。...

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

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

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

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

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

    二、使用JPA实现泛型DAO JPA(Java Persistence API)是一种java持久层标准,提供了一个常用的DAO模式实现。JPA可以与Struts、Spring框架集成,实现用户管理系统的开发。使用JPA可以将业务逻辑代码和持久化代码分离...

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

    例如,可以有一个`BaseDao&lt;T&gt;`接口,其中T代表任意实体类型,然后针对每种实体创建具体的Dao实现类。 在实际开发中,`base`可能是指基础配置文件或者示例代码,包括Spring的bean配置文件(如`beans.xml`)、Struts2...

    泛型DAO,注释详细

    这样,我们就可以为不同的数据实体类(如User、Product等)创建DAO实现,而无需为每个实体类重复编写相同的方法。 接下来,我们可以使用Hibernate或MyBatis等持久层框架实现这个泛型DAO。以Hibernate为例,一个简单...

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

    4. **提升拓展性**:当添加新的数据实体类时,只需简单地声明新的实体类类型,而无需修改已有的DAO实现,易于扩展。 5. **提高可维护性**:代码结构清晰,模块化程度高,易于理解和维护。 在Java Web框架如Struts和...

    基于泛型的通用Dao接口和hibernate的实现

    Hibernate 对泛型Dao接口的实现主要通过继承泛型Dao接口,使用 Hibernate 的 Session 对象来实现数据访问。 Hibernate 对泛型Dao接口的实现的优点: 1. 简化数据访问:Hibernate 对泛型Dao接口的实现可以简化数据...

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

    在实际的Java Web应用中,我们可以结合Spring框架的Hibernate或JPA支持,进一步简化泛型DAO的实现,利用Spring的模板类如JdbcTemplate、HibernateTemplate等,自动处理SQL执行和结果映射。 总的来说,泛型DAO在Java...

    SSH 泛型DAO分页

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

Global site tag (gtag.js) - Google Analytics