BaseDao BaseDaoHibernate

package com.web.base;

import java.io.File;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

/**
 * Generic DAO (Data Access Object) with common methods to CRUD POJOs.
 * 
 * <p>
 * Extend this interface if you want typesafe (no casting necessary) DAO's for
 * your domain objects.
 * 
 * @author <a href="mailto:[email protected]">Bryan Noll</a>
 * @param <T>
 *            a type variable
 * @param <PK>
 *            the primary key for that type
 */
public interface BaseDao<T, PK extends Serializable> {

	/**
	 * Generic method used to get all objects of a particular type. This is the
	 * same as lookup up all rows in a table.
	 * 
	 * @return List of populated objects
	 */
	List<T> getAll();

	/**
	 * Generic method to get an object based on class and identifier. An
	 * ObjectRetrievalFailureException Runtime Exception is thrown if nothing is
	 * found.
	 * 
	 * @param id
	 *            the identifier (primary key) of the object to get
	 * @return a populated object
	 * @see org.springframework.orm.ObjectRetrievalFailureException
	 */
	T get(PK id);

	/**
	 * Checks for existence of an object of type T using the id arg.
	 * 
	 * @param id
	 *            the id of the entity
	 * @return - true if it exists, false if it doesn't
	 */
	boolean exists(PK id);

	/**
	 * Generic method to save an object - handles both update and insert.
	 * 
	 * @param object
	 *            the object to save
	 * @return the persisted object
	 */
	T save(T object);

	/**
	 * Generic method to delete an object based on class and id
	 * 
	 * @param id
	 *            the identifier (primary key) of the object to remove
	 */
	void remove(PK id);
	
	public void removes(PK[] ids);
	
    void remove1(PK id);
	
	public void removes1(PK[] ids);

	/**
	 * Gets all records without duplicates.
	 * <p>
	 * Note that if you use this method, it is imperative that your model
	 * classes correctly implement the hashcode/equals methods
	 * </p>
	 * 
	 * @return List of populated objects
	 */
	List<T> getAllDistinct();

	/**
	 * Find a list of records by using a named query
	 * 
	 * @param queryName
	 *            query name of the named query
	 * @param queryParams
	 *            a map of the query names and the values
	 * @return a list of the records found
	 */
	List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams);
	
	List<T> getByHql(String hql,Object[] objs);
	
	public void updateQuery(final String hql,final Map map);
	
    public List<T> getPageData(final String hql, final Map map, final int page, final int pageSize);
	
	public int getPageSize(final String hql,final Map map);
	
	public List<T> getPageData(final String hql,final Map map);
	
	public  List getAllByHql(String hql,Object[] objs);
	
	public List getBySql(final String sql, Class c);
	
	public BigDecimal getTotalCount(String hql, Map map);
	
	public void saveUploadFile(String eid,File[] files,String[] filesFileName,String[] filesContentType,int[] yxxz);
	
	public void saveUploadFile2(String eid,File[] files,String[] filesFileName,String[] filesContentType,int[] yxxz,String fjlx,String fjlxid);

	public void removes2(PK[] ids,Map session);
}





package com.web.base;

import java.io.File;
import org.apache.struts2.interceptor.SessionAware;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.web.core.utils.EaModelContent;
import com.web.event.vo.Sjfjb;
import com.web.sys.vo.Changelog;
import com.web.sys.vo.Department;
import com.web.sys.vo.Table;
import com.web.sys.vo.TableColumn;
import com.web.utils.FileUtil;
import com.web.utils.Tools;

public class BaseDaoHibernate<T, PK extends Serializable> extends
		HibernateDaoSupport implements BaseDao<T, PK> {
	/**
	 * Log variable for all child classes. Uses LogFactory.getLog(getClass())
	 * from Commons Logging
	 */
	protected final Log log = LogFactory.getLog(getClass());

	private Class<T> persistentClass;

	/**
	 * Constructor that takes in a class to see which type of entity to persist
	 * 
	 * @param persistentClass
	 *            the class type you'd like to persist
	 */
	public BaseDaoHibernate(final Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		return super.getHibernateTemplate().loadAll(this.persistentClass);
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<T> getAllDistinct() {
		Collection result = new LinkedHashSet(getAll());
		return new ArrayList(result);
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public T get(PK id) {
		T entity = (T) super.getHibernateTemplate().get(this.persistentClass,
				id);
// if (entity == null) {
// log.warn("Uh oh, '" + this.persistentClass + "' object with id '"
// + id + "' not found...");
// throw new ObjectRetrievalFailureException(this.persistentClass, id);
// }

		return entity;
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public boolean exists(PK id) {
		T entity = (T) super.getHibernateTemplate().get(this.persistentClass,
				id);
		return entity != null;
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public T save(T object) {
		String type=EaModelContent.OPERATE_INSERT;
		BaseVo bv=(BaseVo)object;
		if(bv!=null&&bv.getId()!=null)
			type=EaModelContent.OPERATE_UPDATE;
		
		T entity = (T) super.getHibernateTemplate().merge(object);
		
		saveLog((BaseVo)entity, type);
		return entity;
	}

	/**
	 * {@inheritDoc}
	 */
	public void remove(PK id) {
		T entity = this.get(id);
		if(entity!=null)
			super.getHibernateTemplate().delete(entity);

		BaseVo bv=(BaseVo)entity;
		saveLog(bv,EaModelContent.OPERATE_DELETE);
	}	
	public void removes(PK[] ids) {
		for(PK id:ids){
			remove(id);
		}
	}
	public void removes2(PK[] ids,Map session) {
		Map map = new HashMap();
		String hql = "from PK t where t.aid=:id ";
		List<Department> departments = (List<Department>) session.get("departments");
		for(PK id:ids){
			map.put("id", id);
			Department d=(Department) super.getHibernateTemplate().load(hql,(Serializable) map);
		departments.remove(d);
		}
		
	}


	public void remove1(PK id) {
		String hql="update "+this.persistentClass.getName().toString()+" t set t.remove=1 where t.id=:id";
		Map map=new HashMap();
		map.put("id", id);
		updateQuery(hql,map);
		
		T entity = this.get(id);
		BaseVo bv=(BaseVo)entity;
		saveLog(bv,EaModelContent.OPERATE_DELETE1);
	}
	public void removes1(PK[] ids) {
		String hql="update "+this.persistentClass.getName().toString()+" t set t.remove=1 where t.id in (:ids)";
		Map map=new HashMap();
		map.put("ids", ids);
		updateQuery(hql,map);		
	}

	public void saveLog(BaseVo bv, String operateType) {
		String classname = persistentClass.getName();
		Table table = EaModelContent.logTableMap.get(classname);
		Date nowdate = Tools.getNowDate();
		try {
			if (table != null) {
				JSONObject json = new JSONObject();
				List<TableColumn> tableColumnList = table.getTableColumnList();
				if (tableColumnList != null) {
					for (TableColumn column : tableColumnList) {
						Object value = PropertyUtils.getProperty(bv, column.getAttributename());
						json.put(column.getName(), value);

					}
				}				
				HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
				Changelog log = new Changelog();
				log.setRequestUrl(request.getRequestURI());
				log.setOperateType(operateType);
				log.setCreated(nowdate);
				log.setCreatedby(bv.getUpdatedby());
				log.setInfo(json.toString());
				Object pk = PropertyUtils.getProperty(bv, "id");
				if (pk != null)
					log.setPk((Long) pk);
				if (StringUtils.isNotEmpty(table.getBupk())) {
					Object buPk = PropertyUtils
							.getProperty(bv, table.getBupk());
					if (buPk != null)
						log.setBuPk(buPk.toString());
				}
				log.setTableId(table.getId());
				getHibernateTemplate().save(log);
			}
		} catch (Exception e) {
			logger.error("插入操作日志异常", e);
			e.printStackTrace();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByNamedQuery(String queryName,
			Map<String, Object> queryParams) {
		String[] params = new String[queryParams.size()];
		Object[] values = new Object[queryParams.size()];
		int index = 0;
		Iterator<String> i = queryParams.keySet().iterator();
		while (i.hasNext()) {
			String key = i.next();
			params[index] = key;
			values[index++] = queryParams.get(key);
		}
		return getHibernateTemplate().findByNamedQueryAndNamedParam(queryName,
				params, values);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getByHql(String hql, Object[] objs) {
		return getHibernateTemplate().find(hql, objs);
	}
	
	public void updateQuery(final String hql,final Map map) {
		try {
			this.getHibernateTemplate().execute(new HibernateCallback() {
				public Object doInHibernate(Session session)
						throws SQLException, HibernateException {
					try {
						Query query = session.createQuery(hql).setProperties(map);
						query.executeUpdate();
						session.close();
						return null;
					} catch (Exception e) {
						session.close();
						return null;
					}
				}
			});
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getPageData(final String hql,final Map map,final int page,final int pageSize){
		List<T> list=getHibernateTemplate().executeFind(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException,SQLException
			{
				int pageNumber=page;
				if(pageNumber==0)
					pageNumber=1;
				List result=session.createQuery(hql).setProperties(map).setFirstResult((pageNumber-1)*pageSize).setMaxResults(pageSize).list();
				return result;
			}			
		});
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getPageData(final String hql,final Map map){
		List<T> list=getHibernateTemplate().executeFind(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException,SQLException
			{
				List result=session.createQuery(hql).setProperties(map).list();
				return result;
			}			
		});
		return list;
	}

	public int getPageSize(final String hql,final Map map) {
		List list=getHibernateTemplate().executeFind(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException,SQLException
			{   
				String hq = hql;
				HashMap hm = (HashMap)map;
				List result=session.createQuery(hql).setProperties(map).list();
				return result;
			}			
		});
		if(list!=null&&list.size()>0)
			return Integer.parseInt(list.get(0).toString());
		else return 0;
	}

	public List getAllByHql(String hql, Object[] objs) {
		return getHibernateTemplate().find(hql, objs);
	}

	public List getBySql(final String sql,Class c) {
		return this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(sql).addEntity(c).list();
	}
	public BigDecimal getTotalCount(final String hql, final Map map) {
		List list=getHibernateTemplate().executeFind(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException,SQLException
			{
				List result=session.createQuery(hql).setProperties(map).list();
				return result;
			}			
		});
		if(list!=null&&list.size()>0)
			return new BigDecimal(list.get(0).toString());
		else return null;
	}

	public void saveUploadFile(String eid, File[] files, String[] filesFileName, String[] filesContentType,int[] yxxz) {
		String path = EaModelContent.uploadfilepath+File.separator+eid;  // 写到指定的路径中   
		File dir = new File(path);  //如果指定的路径没有就创建
		if (!dir.exists()) { 
			dir.mkdirs();
		} 		
		if(files==null)
			return;
		for(int i=0;i<files.length;i++){
			try{
				if(files[i]!=null){
					String wjkzm=FileUtil.getExtensionName(filesFileName[i]);
					String cclj=Tools.getNowTime()+"-"+Tools.getRandom(System.nanoTime())+"."+wjkzm;
					String wjdx=FileUtil.getFileSize(files[i]);
					FileUtils.copyFile(files[i], new File(dir, cclj));
					
					Sjfjb sjfjb=new Sjfjb();
					sjfjb.setEid(eid);
					sjfjb.setWjmc(filesFileName[i]);
					sjfjb.setWjkzm(wjkzm);
					sjfjb.setContenttype(filesContentType[i]);
					sjfjb.setCclj(cclj);
					sjfjb.setWjdx(wjdx);
					sjfjb.setYxxz(yxxz[i]);
					//sjfjb.setXzcs(xzcs);
					getHibernateTemplate().save(sjfjb);
				}				
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	
	public void saveUploadFile2(String eid, File[] files, String[] filesFileName, String[] filesContentType,int[] yxxz,String fjlx,String fjlxid) {
		String path = EaModelContent.uploadfilepath+File.separator+eid;  // 写到指定的路径中   
		File dir = new File(path);  //如果指定的路径没有就创建
		if (!dir.exists()) { 
			dir.mkdirs();
		} 		
		if(files==null)
			return;
		for(int i=0;i<files.length;i++){
			try{
				if(files[i]!=null){
					String wjkzm=FileUtil.getExtensionName(filesFileName[i]);
					String cclj=Tools.getNowTime()+"-"+Tools.getRandom(System.nanoTime())+"."+wjkzm;
					String wjdx=FileUtil.getFileSize(files[i]);
					FileUtils.copyFile(files[i], new File(dir, cclj));
					
					Sjfjb sjfjb=new Sjfjb();
					sjfjb.setEid(eid);
					sjfjb.setWjmc(filesFileName[i]);
					sjfjb.setWjkzm(wjkzm);
					sjfjb.setContenttype(filesContentType[i]);
					sjfjb.setCclj(cclj);
					sjfjb.setWjdx(wjdx);
					sjfjb.setYxxz(yxxz[i]);
					//sjfjb.setXzcs(xzcs);
					sjfjb.setFjlx(fjlx);
					sjfjb.setFjlxid(fjlxid);
					getHibernateTemplate().save(sjfjb);
				}				
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}

}

你可能感兴趣的:(Hibernate)