⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hibernatedaohelper.java

📁 使用WEBWORK,SPRING,HIBERNATE编写的简单的添加
💻 JAVA
字号:
/**
 *文件功能: 
 */
package com.common.dao;

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

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.common.Config;
import com.common.exception.DAOException;
import com.common.util.PaginationSupport;

/**
 * @作者 徐建协
 * @日期 2008-2-19
 */
public class HibernateDaoHelper extends HibernateDaoSupport {
	private Map<String, String> aliasesMap;
	public final static String COUNT_ALIAS = "count";
	protected final static String ALIAS_PREFIX = "alias_";	
	protected final static int DEFAULT_BATCH_SIZE = Config.batchSize;
	private static Log log = LogFactory.getLog(HibernateDaoHelper.class);
	
	private SessionFactory sessionFactory;
	
	private String queryCacheRegion;
    public Map<String, String> getAliasesMap() {
		return aliasesMap;
	}

	public void setAliasesMap(Map<String, String> aliasesMap) {
		this.aliasesMap = aliasesMap;
	}


	public String getQueryCacheRegion() {
		return queryCacheRegion;
	}

	public void setQueryCacheRegion(String queryCacheRegion) {
		this.queryCacheRegion = queryCacheRegion;
	}

	/**
     * Assemble the SQL which carry out the sum of results.
     * 根据传入的查询语句,组装查询的记录数的SQL语句
     * @param SQL
     * @param the summed column's name
     * @param alias 记录别名
     * @return assembled SQL 返回组装好的SQL语句
     */
    public static String getCountSql(String sql, String paginationKey, String alias) {
        
    	String trueAlias = (alias == null) ? COUNT_ALIAS : alias;
        if (StringUtils.isEmpty(sql)) {
            return null;
        }
        //sql=StringUtils.upperCase(sql);
        return (new StringBuilder()).append("select count(").append(paginationKey).append(") as ").append(trueAlias).append(" ").append(sql.substring(sql.indexOf("from"))).toString();
    }	
    /*******************
     * 获取查询结果的记录数
     * @param sql 查询的SQL语句
     * @param alias 查询的字段
     * @return 获取查询结果,一般为记录数
     */
    public int countBySQL(final String sql, final String alias) {
        Integer count = (Integer) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
            	String trueAlias = (alias == null) ? COUNT_ALIAS : alias;
                Query query = session.createSQLQuery(sql).addScalar(trueAlias, Hibernate.INTEGER);
                //query.
                return query.uniqueResult();
            }
        }, true);
        return count == null ? 0 : count.intValue();
    }  
    /*******************
     * 获取查询结果的记录数
     * @param sql 查询的SQL语句
     * @param alias 查询的字段
     * @return 获取查询结果,一般为记录数
     */
    public int countBySQL(final String sql, final String alias,final Object values[]) {
        Integer count = (Integer) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
            	String trueAlias = (alias == null) ? COUNT_ALIAS : alias;
                Query query = session.createSQLQuery(sql).addScalar(trueAlias, Hibernate.INTEGER);
                if (values!=null&&values.length>0){
                	for (int index = 0; index < values.length;index++) {
						Object value = values[index];
						query.setParameter(index, value);
					}
                }
                return query.uniqueResult();
            }
        }, true);
        return count == null ? 0 : count.intValue();
    }      
    
    /*******************
     * 获取查询结果的第一条记录的第一个字段
     * @param sql 查询的SQL语句
     * @param alias 查询的字段
     * @return 获取查询结果
     */
    public String getUniqueResult(final String sql, final String alias,final Object values[]) {
        String res = (String) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
            	String trueAlias = (alias == null) ? COUNT_ALIAS : alias;
                Query query = session.createSQLQuery(sql).addScalar(trueAlias, Hibernate.STRING);
                if (values!=null&&values.length>0){
                	for (int index = 0; index < values.length;index++) {
						Object value = values[index];
						query.setParameter(index, value);
					}
                }
                return query.uniqueResult();
            }
        }, true);
        return res;
    }     
    @SuppressWarnings("unchecked")
    public List findBySQL(final String sql, final String alias, final Class entityClass,final Object values[], final boolean cacheable, final int startIndex, final int maxResultCount) {
        return (List) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                Query query = (alias == null) ? session.createSQLQuery(sql).addEntity(entityClass) : session.createSQLQuery(sql).addEntity(alias, entityClass);
            	//Query query =  session.createSQLQuery(sql);
                if (values!=null&&values.length>0){
                	for (int index = 0; index < values.length;index++) {
						Object value = values[index];
						query.setParameter(index, value);
					}
                }
                if (cacheable) {
                    query.setCacheable(true);
                    if (getQueryCacheRegion() != null) {
                        query.setCacheRegion(getQueryCacheRegion());
                    }
                }
                if (maxResultCount != -1) {
                    query.setMaxResults(maxResultCount);
                }
                if (startIndex != -1) {
                    query.setFirstResult(startIndex);
                }
                
                return query.list();
            }
        }, true);
    }
    public PaginationSupport findBySQL(PaginationSupport paginationSupport,String countSQL,String countAlias,String sql,String sqlAlias,Object[] values, final Class entityClass, final boolean cacheable) {   
    	paginationSupport.setTotalCount(countBySQL(countSQL,countAlias,values));
    	paginationSupport.setItems(findBySQL(sql,sqlAlias,entityClass,values,cacheable,paginationSupport.getStartIndex(),paginationSupport.getPageSize()));
    	return paginationSupport;
    }   
    /********************
     * 批量执行hibernate的hql语句
     * @param hql
     * @param values
     */
    public void batchHQL(final String hql,final Object[] values){
    	getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						try {
							Query query=session.createQuery(hql);
							if (values!=null&&values.length>0){
			                	for (int index = 0; index < values.length;index++) {
									Object value = values[index];
									query.setParameter(index, value);
								}
			                }
							query.executeUpdate();
						} catch (HibernateException e) {
							e.printStackTrace();
							log.error("批量执行hql出错:" + e);
							throw new DAOException("批量执行hql出错:"
											+ e.getMessage());
						} catch (DataAccessException e) {
							e.printStackTrace();
							log.error("批量执行hql出错:" + e);
							throw new DAOException(e);
						} catch (Throwable e) {
							e.printStackTrace();
							log.error("系统错误:" + e);
							throw new DAOException(e);
						}
						return null;
					}
				},true);	
    }
    public void flush(){
    	getHibernateTemplate().flush();
    	getHibernateTemplate().clear();
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	
	}    
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -