泛型dao

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,sql,Hibernate,.net,orm)