看到很多人都发布了hibernate dao 我都看了下 也写了一份 很多人都提了建议,将查询抽取出来这个建议不错,我这个就是吸取了大家的建议,还加了分页标签。

basedao接口:
package org.ywq.common;

import java.io.Serializable;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;

public interface IDAO<T,ID extends Serializable> {

	/**
	 * 查询类clazz的所有对象.
	 * 
	 * @param clazz
	 *            the type of objects (a.k.a. while table) to get data from
	 * @return List of populated objects
	 */
	public List<T> getObjects(Class<T> clazz);

	/**
	 * 根据类名和主键得到一个对象.
	 * 
	 * @param clazz
	 *            model class to lookup
	 * @param id
	 *            the identifier (primary key) of the class
	 * @return a populated object
	 * @see org.springframework.orm.ObjectRetrievalFailureException
	 */
	public Object getObject(Class<T> clazz, Serializable id);

	/**
	 * 插入一个对象.
	 * 
	 * @param o
	 *            the object to save
	 */
	public Object save(Object o);

	/**
	 * 持久化一个对象,包括更新或插入.
	 * 
	 * @param o
	 *            the object to save
	 * 
	 */
	public Object saveOrUpdate(Object o);

	/**
	 * 更新一个对象.
	 * 
	 * @param object
	 */
	public Object update(Object object);

	/**
	 * 根据类和主键,删除一个对象.
	 * 
	 * @param clazz
	 *            model class to lookup
	 * @param id
	 *            the identifier (primary key) of the class
	 */
	public void removeObject(Class<T> clazz, Serializable id);

	/**
	 * 删除一个对象.
	 */
	public void removeObject(Object object);

	/**
	 * 批量删除对象.
	 * 
	 * @param clazz
	 * @param ids
	 */
	public void removeBatch(Class<T> clazz, Serializable[] ids);

	/**
	 * 根据HQL查询设置.
	 * 
	 * @param filter
	 * @return
	 */
	public List<T> find(String query);

	/**
	 * 根据查询设置得到查询结果
	 * 
	 * @param query
	 * @return
	 */
	public List<T> find(QueryBuilder<T> queryBuilder);

	/**
	 * 
	 * @param currentPage
	 *            当前页码
	 * @param pageSize
	 *            页大小
	 * @param queryBuilder
	 *            查询类
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public PageModel find(Integer currentPage, Integer pageSize, QueryBuilder queryBuilder);

	/**
	 * 更新对象.
	 * 
	 * @param object
	 *            需要更新的对象.
	 */
	public void refresh(Object object);

	/**
	 * 更新到数据库中.
	 */
	public void flush();

	/**
	 * 根据查询设置,得到分页的数据结果集.
	 * 
	 * @param query
	 * @param start
	 *        offset
	 * @param length
	 *     size
	 * @return
	 */
	public List<T> find(String query, Integer start, Integer length);

	/**
	 * 
	 * @param queryBulider
	 *        查询条件
	 * @param currentPage
	 *        当前页
	 * @param pageSize
	 *  
	 * @return
	 */
	public List<T> find(QueryBuilder<T> queryBulider, Integer currentPage, Integer pageSize);

	/**
	 * 根据条件查询.
	 * 
	 * @param hql
	 *            hql语句.
	 * @param param
	 *            参数.
	 * @return 查询结果.
	 */
	public List<T> find(String hql, Serializable param);

	/**
	 * 根据条件查询相关结果.
	 * 
	 * @param clazz
	 *            要查询的对象.
	 * @param criterions
	 *            查询条件.
	 * @return 查询结果.
	 */
	public List<T> getList(Class<T> clazz, Criterion[] criterions);

	/**
	 * @param clazz
	 * @param criterions
	 * @return
	 */
	public Object getFirst(Class<T> clazz, Criterion[] criterions);

	/**
	 * @param class1
	 * @param 条件查询数组
	 * @param 排序
	 * @return
	 */
	public List<T> getList(Class<T> class1, Criterion[] criterions,
			Order[] orders);

	/**
	 * @param className
	 * @param criterions
	 * @return
	 */
	public List<T> getList(String className, Criterion[] criterions);

	/**
	 * @param className
	 * @param sequenceName
	 * @return
	 */
	public List<T> getNextId(String sequenceName);

	/**
	 * @param qb
	 * @return
	 */
	public int count(QueryBuilder<T> qb);

	/*
	 * 
	 */
	public int count(String hql);

	/**
	 * 执行SQL语句, 返回影响结果的行数
	 * 
	 * @param sql
	 * @return
	 */
	public int updateBySql(String sql);

	/**
	 * 批量修改对象
	 * 
	 * @param objs
	 * @param batchSize
	 */
	public void updateBatch(List<T> objs, int batchSize);

}



查询类接口:


package org.ywq.common;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;

/**
 * 查询过滤类.
 * 
 */
public interface QueryBuilder<T> extends Serializable {
	
	public void setDc(DetachedCriteria ec);

	public abstract QueryBuilder<T> clone();

	/**
	 * 判断是否相等
	 * @param propertyName
	 * @param value
	 */
	public abstract QueryBuilder<T> eq(String propertyName, Object value);

	/**
	 * 判断是否匹配
	 * @param propertyName
	 * @param value
	 */
	public abstract QueryBuilder<T> like(String propertyName, Object value);

	/**
	 * 根据matchMode判断是否匹配
	 * @param propertyName
	 * @param value
	 * @param matchMode
	 */
	public abstract QueryBuilder<T> like(String propertyName, String value,
			MatchMode matchMode);

	/**
	 * 根据matchMode判断是否匹配
	 * @param propertyName
	 * @param value
	 * @param matchMode
	 */
	public abstract QueryBuilder<T> ilike(String propertyName, String value,
			MatchMode matchMode);

	/**
	 * 判断时候不等
	 * @param propertyName
	 * @param value
	 */
	public abstract QueryBuilder<T> ilike(String propertyName, Object value);

	/**
	 * 判断是否大于
	 * @param propertyName
	 * @param value
	 */
	public abstract QueryBuilder<T> gt(String propertyName, Object value);

	/**
	 * 判断是否小于
	 * @param propertyName
	 * @param value
	 */
	public abstract QueryBuilder<T> lt(String propertyName, Object value);

	/**
	 * 判断是否小于等于
	 * @param propertyName
	 * @param value
	 */
	public abstract QueryBuilder<T> le(String propertyName, Object value);

	/**
	 * 判断是否大于等于
	 * @param propertyName
	 * @param value
	 */
	public abstract QueryBuilder<T> ge(String propertyName, Object value);

	/**
	 * 不等于.
	 * @param propertyName
	 * @param value
	 */
	public QueryBuilder<T> notEq(String propertyName, Object value);

	/**
	 * 判断是否在给定的区间里
	 * @param propertyName
	 * @param lo
	 * @param hi
	 */
	public abstract QueryBuilder<T> between(String propertyName, Object lo,
			Object hi);

	/**
	 * 判断是否在给定的数组里
	 * @param propertyName
	 * @param values
	 */
	public abstract QueryBuilder<T> in(String propertyName, Object[] values);

	/**
	 * 判断是否在给定的集合里
	 * @param propertyName
	 * @param values
	 */
	public abstract QueryBuilder<T> in(String propertyName, Collection<T> values);

	/**
	 * 判断是否为空
	 * @param propertyName
	 */
	public abstract QueryBuilder<T> isNull(String propertyName);

	/**
	 * 判断属性值是否相等
	 * @param propertyName
	 * @param otherPropertyName
	 */
	public abstract QueryBuilder<T> eqProperty(String propertyName,
			String otherPropertyName);

	/**
	 * 判断属性值是否小于
	 * @param propertyName
	 * @param otherPropertyName
	 */
	public abstract QueryBuilder<T> ltProperty(String propertyName,
			String otherPropertyName);

	/**
	 * 判断属性值是否小于等于
	 * @param propertyName
	 * @param otherPropertyName
	 */
	public abstract QueryBuilder<T> leProperty(String propertyName,
			String otherPropertyName);

	/**
	 * 判断是否不等于
	 * @param propertyName
	 */
	public abstract QueryBuilder<T> isNotNull(String propertyName);

	/**
	 * @param propertyNameValues
	 * @return
	 */
	public abstract QueryBuilder<T> allEq(Map<T, T> propertyNameValues);

	/** 
	 * 添加排序
	 * @param orderBy
	 * @return
	 */
	public abstract QueryBuilder<T> addOrderBy(Order orderBy);

	/**
	 * 查询条件
	 * 不建议使用
	 * @param criterion
	 * @return
	 */
	public abstract QueryBuilder<T> addCriterion(Criterion criterion);

	/**
	 * 
	 * @return
	 */
	public abstract List<Order> getOrderBys();

	/**
	 * 
	 * @return
	 */
	public abstract DetachedCriteria getDetachedCriteria();

	public abstract Class<T> getClazz();

}



basedao 实现类:
package org.ywq.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

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.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.util.Assert;
import org.ywq.common.utils.ObjectWriteorRead;

/**
 * 基本实现类
 * 
 * @spring.property name="sessionFactory" ref="sessionFactory" type="bean"
 *                  注入sessionFactory
 */
public class BaseDAOHibernate<T> extends HibernateDaoSupport implements
		IDAO<T, Serializable> {

	@SuppressWarnings("unchecked")
	public PageModel<T> find(final Integer currentPage, final Integer pageSize,
			final QueryBuilder qb) {
		QueryBuilder newqb = null;
		if (qb != null) {
			ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
			ObjectWriteorRead.writeObject(qb, byteOut);// 序列化对象, 这里需要用到对象拷贝,一直没有好的办法,用克隆的方法没效果,所有暂时也不考虑效率了,这里希望大家提点建议
			ByteArrayInputStream bytein = new ByteArrayInputStream(byteOut
					.toByteArray());
			newqb = (QueryBuilder) ObjectWriteorRead.readObject(bytein);// 还原对象,以实现拷贝对象
			Integer total = this.count(newqb);
			PageModel pm = new PageModel();
			pm.setDatas(this.find(qb, currentPage, pageSize));
			pm.setTotal(total);
			pm.setPagesize(pageSize);
			pm.setTotalPage((total + pageSize - 1) / pageSize);
			pm.setCurrenPage((currentPage));
			return pm;
		}
		return null;
	}

	protected final Log log = LogFactory.getLog(getClass());

	public BaseDAOHibernate() {
		System.out.println("creating BaseDAOHibernate... ");
	}

	@SuppressWarnings("unchecked")
	public List<T> getObjects(Class<T> clazz) {
		Assert.notNull(clazz, "要查询的对象类型不能为空!");
		return getHibernateTemplate().loadAll(clazz);
	}

	public Object getObject(Class<T> clazz, Serializable id) {
		Assert.notNull(clazz, "要查询的对象类型不能为空!");
		Assert.notNull(id, "要查询的对象主键不能为空!");
		return getHibernateTemplate().get(clazz, id);
	}

	public Object save(Object o) {
		Assert.notNull(o, "要保存的对象不能为空!");
		getHibernateTemplate().save(o);
		return o;
	}

	public Object saveOrUpdate(Object o) {
		Assert.notNull(o, "要保存或更新的对象类型不能为空!");
		getHibernateTemplate().saveOrUpdate(o);
		return o;
	}

	public Object update(Object object) {
		Assert.notNull(object, "要更新的对象类型不能为空!");
		getHibernateTemplate().update(object);
		return object;
	}

	@SuppressWarnings("unchecked")
	public void removeObject(Class<T> clazz, Serializable id) {
		Assert.notNull(clazz, "要移除的对象类型不能为空!");
		Assert.notNull(id, "要移除的对象主键不能为空!");
		Object object = getObject(clazz, id);
		if (object != null) {
			getHibernateTemplate().delete(object);
		}
	}

	public void removeObject(Object object) {
		Assert.notNull(object, "要移除的对象不能为空!");
		getHibernateTemplate().delete(object);
	}

	public void removeBatch(final Class<T> clazz, final Serializable[] ids) {
		Assert.notNull(clazz, "要移除的对象类型不能为空!");
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				for (int i = 0; i < ids.length; i++) {
					Object obj = session.load(clazz, ids[i]);
					if (obj != null) {
						session.delete(obj);
					} else {
						log.warn("无法删除主键为:" + ids[i] + "的" + clazz.getName());
					}
				}
				return null;
			}
		});
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String query) {
		Assert.notNull(query, "查询语句不能为空!");
		return getHibernateTemplate().find(query);
	}

	public void refresh(Object object) {
		getHibernateTemplate().refresh(object);
	}

	public void flush() {
		getHibernateTemplate().flush();
	}

	public List<T> find(String query, Integer start, Integer length) {
		return getObjects(query, start, length);
	}

	@SuppressWarnings("unchecked")
	public List<T> find(final QueryBuilder queryBuilder,
			final Integer currentPage, final Integer pageSize) {
		if (queryBuilder != null) {
			return (List<T>) getHibernateTemplate().execute(
					new HibernateCallback() {
						public Object doInHibernate(Session session)
								throws HibernateException, SQLException {
							DetachedCriteria dc = queryBuilder
									.getDetachedCriteria();
							for (Object or : queryBuilder.getOrderBys()) {
								Order order = (Order) or;
								dc.addOrder(order);
							}
							if (currentPage != null && pageSize != null) {
								Criteria crit = dc
										.getExecutableCriteria(session);
								crit.setFirstResult((currentPage - 1)
										* pageSize);
								crit.setMaxResults(pageSize);
							}
							return dc.getExecutableCriteria(session).list();
						}
					}, true);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<T> getObjects(final String queryString, final int position,
			final int length) {
		Assert.notNull(queryString, "查询语句不能为空!");
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(queryString);
				query.setFirstResult(position);
				query.setMaxResults(length);
				List lt = query.list();

				return lt;
			}
		});
	}

	/*
	 * (非 Javadoc)
	 * 
	 */
	public List<T> find(final QueryBuilder<T> queryBuilder) {
		if (queryBuilder != null) {
			return this.find(queryBuilder, null, null);
		}
		return null;
	}

	/**
	 * @param hql
	 * @param param
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> find(final String hql, final Serializable param) {
		Assert.notNull(hql, "查询语句不能为空!");
		Assert.notNull(param, "查询参数不能为空!");

		return getHibernateTemplate().find(hql, param);
	}

	/**
	 * @param clazz
	 * @param criterions
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> getList(final Class<T> clazz, final Criterion[] criterions) {
		Assert.notNull(clazz, "要查询的类不能为空!");
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria query = session.createCriteria(clazz);
				if (criterions != null && criterions.length > 0) {
					for (int i = 0; i < criterions.length; i++) {
						query.add(criterions[i]);
					}
				}
				return query.list();
			}
		});
	}

	/**
	 * 得到查到的最前一个对象.
	 * 
	 * @param clazz
	 *            类名.
	 * @param criterions
	 *            查询条件.
	 * @return 查询得到的结果.
	 */
	public Object getFirst(Class<T> clazz, Criterion[] criterions) {
		List<T> lt = getList(clazz, criterions);
		if (lt != null && !lt.isEmpty()) {
			return lt.get(0);
		}
		return null;
	}

	/**
	 * @param clazz
	 * @param criterions
	 * @param orders
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> getList(final Class<T> clazz, final Criterion[] criterions,
			final Order[] orders) {
		Assert.notNull(clazz, "要查询的类不能为空!");
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria criteria = session.createCriteria(clazz);
				if (criterions != null && criterions.length > 0) {
					for (int i = 0; i < criterions.length; i++) {
						criteria.add(criterions[i]);
					}
				}
				if (orders != null && orders.length > 0) {
					for (int i = 0; i < orders.length; i++) {
						criteria.addOrder(orders[i]);
					}
				}
				return criteria.list();
			}
		});
	}

	/**
	 * @param className
	 * @param criterions
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> getList(final String className, final Criterion[] criterions) {
		Assert.notNull(className, "要查询的类名不能为空");
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria criteria = null;
				try {
					criteria = session.createCriteria(Class.forName(className));
				} catch (ClassNotFoundException e) {
					logger
							.error(
									"$HibernateCallback.doInHibernate(Session) - 找不到类错误 - e=" + e, e); //$NON-NLS-1$
					throw new IllegalArgumentException("传入的类名是错误的,classname = "
							+ className);
				}
				if (criterions != null && criterions.length > 0) {
					for (int i = 0; i < criterions.length; i++) {
						criteria.add(criterions[i]);
					}
				}
				return criteria.list();
			}
		});
	}

	/**
	 * @param className
	 * @param sequenceName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> getNextId(final String sequenceName) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = null;
				query = session.createSQLQuery("select " + sequenceName
						+ ".nextval from dual");
				return query.list();
			}
		});
	}

	public int count(final String hql) {
		return ((Integer) getHibernateTemplate().execute(
				new HibernateCallback() {

					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session.createQuery(hql);
						return query.setProperties(Projections.rowCount())
								.uniqueResult();
					}
				}, true)).intValue();
	}

	/**
	 * @param qb
	 * @return
	 */
	public int count(final QueryBuilder<T> queryBuilder) {
		return ((Integer) getHibernateTemplate().execute(
				new HibernateCallback() {

					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						System.out.println(session.isOpen());
						DetachedCriteria dc = queryBuilder
								.getDetachedCriteria();
						Criteria ct = dc.getExecutableCriteria(session);
						return ct.setProjection(Projections.rowCount())
								.uniqueResult();
					}
				}, true)).intValue();
	}

	public int updateBySql(final String sql) {
		super.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				int iRet = session.createSQLQuery(sql).executeUpdate();
				return iRet;
			}
		});
		return -1;
	}

	public void updateBatch(final List<T> objs, final int batchSize) {
		super.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				int count = 0;
				for (Object o : objs) {
					session.update(o);
					if (++count % batchSize == 0) {
						session.flush();
						session.clear();
					}
				}
				return true;
			}
		});

	}

}





查询实现类:

package org.ywq.common;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 * 使用hibernate进行查询的实现.
 * 
 */
public class HibernateQueryBuilder<T> implements QueryBuilder<T>, Serializable,
		Cloneable {

	@SuppressWarnings("unchecked")
	public HibernateQueryBuilder<T> clone() {
		HibernateQueryBuilder<T> qb = null;
		try {
			qb = (HibernateQueryBuilder<T>) super.clone();

		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return qb;

	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -7000654904767633672L;

	private DetachedCriteria dc = null;

	private List<Order> orderLists = new ArrayList<Order>();

	private Class<T> clazz = null;

	public HibernateQueryBuilder(Class<T> clazz) {
		this.clazz = clazz;
		dc = DetachedCriteria.forClass(clazz);
	}

	public Class<T> getClazz() {
		return clazz;
	}

	public void setDc(DetachedCriteria dc) {
		this.dc = dc;
	}

	public QueryBuilder<T> eq(String propertyName, Object value) {
		if (isNotEmpty(value)) {
			dc.add(Restrictions.eq(propertyName, value));
		}
		return this;
	}

	/**
	 * 不等于.
	 * 
	 * @param propertyName
	 * @param value
	 * @return
	 */
	public QueryBuilder<T> notEq(String propertyName, Object value) {
		if (isNotEmpty(value)) {
			dc.add(Restrictions.ne(propertyName, value));
		}
		return this;
	}

	private boolean isNotEmpty(Object value) {
		return value != null && value.toString().trim().length() > 0;
	}

	public QueryBuilder<T> like(String propertyName, Object value) {
		if (isNotEmpty(value)) {
			dc.add(Restrictions.like(propertyName, value));
		}
		return this;
	}

	public QueryBuilder<T> like(String propertyName, String value,
			MatchMode matchMode) {
		if (isNotEmpty(value)) {
			dc.add(Restrictions.like(propertyName, value, matchMode));
		}
		return this;
	}

	public QueryBuilder<T> ilike(String propertyName, String value,
			MatchMode matchMode) {
		if (isNotEmpty(value)) {
			dc.add(Restrictions.ilike(propertyName, value, matchMode));

		}
		return this;
	}

	public QueryBuilder<T> ilike(String propertyName, Object value) {
		if (isNotEmpty(value)) {
			dc.add(Restrictions.ilike(propertyName, value));
		}
		return this;
	}

	public QueryBuilder<T> gt(String propertyName, Object value) {
		if (isNotEmpty(value)) {
			dc.add(Restrictions.gt(propertyName, value));
		}
		return this;
	}

	public QueryBuilder<T> lt(String propertyName, Object value) {
		if (isNotEmpty(value)) {
			dc.add(Restrictions.lt(propertyName, value));
		}
		return this;
	}

	public QueryBuilder<T> le(String propertyName, Object value) {
		if (isNotEmpty(value)) {
			dc.add(Restrictions.le(propertyName, value));
		}
		return this;
	}

	public QueryBuilder<T> ge(String propertyName, Object value) {
		if (isNotEmpty(value)) {
			dc.add(Restrictions.ge(propertyName, value));
		}
		return this;
	}

	public QueryBuilder<T> between(String propertyName, Object lo, Object hi) {
		if (isNotEmpty(lo) && isNotEmpty(hi)) {
			dc.add(Restrictions.between(propertyName, lo, hi));
		} else if (isNotEmpty(lo)) {
			dc.add(Restrictions.ge(propertyName, lo));
		} else if (isNotEmpty(hi)) {
			dc.add(Restrictions.le(propertyName, hi));
		}
		return this;
	}

	public QueryBuilder<T> in(String propertyName, Object[] values) {
		if (values != null && values.length > 0) {
			dc.add(Restrictions.in(propertyName, values));
		}
		return this;
	}

	public QueryBuilder<T> in(String propertyName, Collection<T> values) {
		if (values != null && values.size() > 0) {
			dc.add(Restrictions.in(propertyName, values));
		}
		return this;
	}

	public QueryBuilder<T> isNull(String propertyName) {
		dc.add(Restrictions.isNull(propertyName));
		return this;
	}

	public QueryBuilder<T> eqProperty(String propertyName,
			String otherPropertyName) {
		dc.add(Restrictions.eqProperty(propertyName, otherPropertyName));
		return this;
	}

	public QueryBuilder<T> ltProperty(String propertyName,
			String otherPropertyName) {
		dc.add(Restrictions.ltProperty(propertyName, otherPropertyName));
		return this;
	}

	public QueryBuilder<T> leProperty(String propertyName,
			String otherPropertyName) {
		dc.add(Restrictions.leProperty(propertyName, otherPropertyName));
		return this;
	}

	public QueryBuilder<T> isNotNull(String propertyName) {
		dc.add(Restrictions.isNotNull(propertyName));
		return this;

	}

	public QueryBuilder<T> allEq(Map<T, T> propertyNameValues) {
		dc.add(Restrictions.allEq(propertyNameValues));
		return this;
	}

	public QueryBuilder<T> addOrderBy(Order orderBy) {
		orderLists.add(orderBy);
		return this;
	}

	public DetachedCriteria getDetachedCriteria() {
		return dc;
	}

	public List<Order> getOrderBys() {
		return orderLists;
	}

	public QueryBuilder<T> addCriterion(Criterion criterion) {
		if (criterion != null) {
			dc.add(criterion);
		}
		return this;
	}

	@SuppressWarnings("unchecked")
	public boolean equals(Object object) {
		if (!(object instanceof HibernateQueryBuilder)) {
			return false;
		}
		HibernateQueryBuilder<T> rhs = (HibernateQueryBuilder<T>) object;
		return new EqualsBuilder().append(this.clazz, rhs.clazz).isEquals();
	}

	public int hashCode() {
		return new HashCodeBuilder(-2022315247, 1437659757).append(this.clazz)
				.toHashCode();
	}

	public String toString() {
		return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
				.append("orderLists", this.orderLists).append("clazz",
						this.clazz).toString();
	}

}




分页bean:
package org.ywq.common;

import java.util.List;

/**
 * @author ai5qiangshao  E-mail:[email protected]
 * @version 创建时间:Aug 5, 2009 9:47:42 PM
 * @Package org.ywq.common
 * @Description 类说明
 */
public class PageModel<T> {
	private List<T> datas;

	private Integer total;
	
	private Integer totalPage=1;
	
	private Integer pagesize;
	
	private Integer currenPage=1;

	public Integer getCurrenPage() {
		return currenPage;
	}

	public void setCurrenPage(Integer currenPage) {
		this.currenPage = currenPage;
	}

	public Integer getPagesize() {
		return pagesize;
	}

	public void setPagesize(Integer pagesize) {
		this.pagesize = pagesize;
	}

	public List<T> getDatas() {
		return datas;
	}

	public void setDatas(List<T> datas) {
		this.datas = datas;
	}

	public Integer getTotal() {
		return total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}

	public Integer getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(Integer totalPage) {
		this.totalPage = totalPage;
	}

	

}




我的分页标签:支持条件筛选,因为每次翻页都是做的表单提交,因此再jsp页面使用时
需要用表单包围;
package org.ywq.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 * @author ai5qiangshao E-mail:[email protected]
 * @version 创建时间:Aug 7, 2009 10:05:29 AM
 * @Package org.ywq.tag
 * @Description 类说明
 */
public class PageTag extends SimpleTagSupport {

	public PageTag() {
	}

	private String currentPage;
	private String totalPage;

	private String url;

	private String theme = "both";

	public String getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(String currentPage) {
		this.currentPage = currentPage;
	}

	public String getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(String totalPage) {
		this.totalPage = totalPage;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String submitAction() {
		StringBuffer bf = new StringBuffer();
		bf.append("<script language=\"");
		bf.append("JavaScript");
		bf.append("\"").append(">").append("\n");
		bf.append("function topage(");
		bf.append("action");
		bf.append("){");
		bf.append("\n");
		bf.append("var form = document.forms[0];").append("\n");
		bf.append("form.action=action;");
		bf.append("\n");
		bf.append("form.submit();");
		bf.append("}\n");
		bf.append("</script>");
		return bf.toString();
	}

	@Override
	public void doTag() throws JspException, IOException {
		JspWriter out = super.getJspContext().getOut();
		StringBuffer bf = new StringBuffer();
		bf.append(this.submitAction());
		if (theme.equals("both")) {
			bf.append(this.text());
		} else if (theme.equals("number")) {
			bf.append(this.number());
		} else if (theme.equals("text")) {
			bf.append(this.text());
		}

		//System.out.println(bf.toString());
		out.println(bf.toString());
	}

	private String number() {
		String pageNoStr = getPageNoStr();
		System.out.println(pageNoStr);
		StringBuffer str = new StringBuffer();
		Integer totalInt = Integer.valueOf(totalPage);
		str.append("[ ");
		if (totalInt == 1) {
			str.append("<strong>1</strong> ");
		} else {
			int cpageInt = Integer.parseInt(this.getCurrentPage());
			System.out.println(cpageInt + "============当前页");
			int v = (cpageInt - 4) > 0 ? (cpageInt - 4) : 1;
			int v1 = (cpageInt + 4) < totalInt ? (cpageInt + 4) : totalInt;
			if (v1 == totalInt) {
				v = totalInt - 6;
				v = (v <= 0 ? 1 : v); // 如果为负数,则修改为1
			} else if (v == 1 && v1 < totalInt) {
				v1 = totalInt > 6 ? 6 : totalInt;
			}
			// 10个为一组显示

			for (int i = v; i <= v1; i++) {
				if (cpageInt == i) { // 当前页要加粗显示
					str.append("<strong>" + i + "</strong> ");
				} else {
					str.append("<a href=\"").append("javascript:").append("topage('" + url + pageNoStr + i + "')");
					str.append("\"").append(">").append(i).append("</a>");
					str.append("&nbsp;");
				}
			}
		}

		str.append("]");
		return str.toString();
	}

	private String text() {
		StringBuilder str = new StringBuilder();
		String pageNoStr = getPageNoStr();
		int cpageInt = Integer.parseInt(currentPage);
		if (currentPage.equals(totalPage)) {
			if ("1".equals(totalPage)) {
				str.append("[第 " + currentPage + " 页]");
				str.append(" [共 " + totalPage + " 页]");
			} else {
				str.append("<a href=\"").append("javascript:").append(
						"topage('" + url + pageNoStr + 1 + "')");
				str.append("\"").append(">").append("[首页]").append("</a>")
						.append("&nbsp;&nbsp;");

				str.append("<a href=\"").append("javascript:").append(
						"topage('" + url + pageNoStr + (cpageInt - 1) + "')");
				str.append("\"").append(">").append("[上一页]").append("</a>")
						.append("&nbsp;&nbsp;");

				if (this.theme.equals("both")) {
					str.append(this.number());
				}
				str.append("<a href=\"").append("javascript:").append(
						"topage('" + url + pageNoStr + totalPage + "')");
				str.append("\"").append(">").append("[末页]").append("</a>")
						.append("&nbsp;&nbsp;");

			}
		} else {

			if ("1".equals(currentPage)) {
				str.append("<a href=\"").append("javascript:").append(
						"topage('" + url + pageNoStr + 1 + "')");
				str.append("\"").append(">").append("[首页]").append("</a>")
						.append("&nbsp;&nbsp;");
				
				if (this.theme.equals("both")) {
					str.append(this.number());
				}
				
				str.append("<a href=\"").append("javascript:").append(
						"topage('" + url + pageNoStr + (cpageInt + 1) + "')");
				str.append("\"").append(">").append("[下一页]").append("</a>")
						.append("&nbsp;&nbsp;");

				str.append("<a href=\"").append("javascript:").append(
						"topage('" + url + pageNoStr + totalPage + "')");
				str.append("\"").append(">").append("[末页]").append("</a>")
						.append("&nbsp;&nbsp;");
				
			} else {
				str.append("<a href=\"").append("javascript:").append(
						"topage('" + url + pageNoStr + 1 + "')");
				str.append("\"").append(">").append("[首页]").append("</a>")
						.append("&nbsp;&nbsp;");

				str.append("<a href=\"").append("javascript:").append(
						"topage('" + url + pageNoStr + (cpageInt - 1) + "')");
				str.append("\"").append(">").append("[上一页]").append("</a>")
						.append("&nbsp;&nbsp;");
				if (this.theme.equals("both")) {
					str.append(this.number());
				}

				str.append("<a href=\"").append("javascript:").append(
						"topage('" + url + pageNoStr + (cpageInt + 1) + "')");
				str.append("\"").append(">").append("[下一页]").append("</a>")
						.append("&nbsp;&nbsp;");

				str.append("<a href=\"").append("javascript:").append(
						"topage('" + url + pageNoStr + totalPage + "')");
				str.append("\"").append(">").append("[末页]").append("</a>")
						.append("&nbsp;&nbsp;");
			}

		}

		return str.toString();
	}

	public static void main(String[] args) {
		PageTag tag = new PageTag();
		tag.setCurrentPage("2");
		tag.setTotalPage("30");
		tag.setUrl("http://localhost:8080/test.do");
		tag.setTheme("text");
		System.out.println(tag.text());

	}

	public String getTheme() {
		return theme;
	}

	public void setTheme(String theme) {
		this.theme = theme;
	}

	public String getPageNoStr() {
		if (url.indexOf("?") != -1) {
			return "&pageNo=";
		} else
			return "?pageNo=";
	}
}




tld文件:


<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
  "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
	<tlib-version>1.0</tlib-version>
	<jsp-version>1.2</jsp-version>
	<short-name>page</short-name>
	<uri>http://[email protected]/page</uri>
	<display-name>page</display-name>
	<tag>
		<name>pg</name>
		<tag-class>org.ywq.tag.PageTag</tag-class>
		<body-content>empty</body-content>
		<attribute>
			<name>currentPage</name>
			<required>true</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>
		<attribute>
			<name>totalPage</name>
			<required>true</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>
		<attribute>
			<name>url</name>
			<required>true</required>
		</attribute>
		<attribute>
			<name>theme</name>
			<required>false</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>


	</tag>


</taglib>



action里代码日下:
String strnum=request.getParameter("pageNo");
			System.out.println(strnum);
			Integer page = Integer.parseInt(strnum==null?"1":strnum);
			String where=((DynaActionForm)form).getString("query");
			System.out.println(where+"===========");
			request.setAttribute("pageModel", userService.list(page, 5,where));
			
			return mapping.findForward("list");





jsp页面使用如下:

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib prefix="page" uri="/WEB-INF/page.tld"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>My JSP 'pagesplit.jsp' starting page</title>
	</head>

	<body>
		<table>
			<tr>
				<td>
					ID
				</td>
				<td>
					NAME
				</td>
				<td>
					AGE
				</td>
				<td>
					SEX
				</td>
			</tr>

			<c:forEach var="user" items="${pageModel.datas}">
				<tr>
					<td>
						${user.uid }
					</td>
					<td>
						${user.uname }
					</td>
					<td>
						${user.usex }
					</td>
					<td>
						${user.uage }
					</td>
				</tr>
			</c:forEach>

		</table>

		<c:if test="${! empty pageModel.datas}">
			<html:form action="user/userManager.do?method=list" method="post">
				<html:text property="query" />


				<page:pg url="/SSH/user/userManager.do?method=list"
					totalPage="${pageModel.totalPage}"
					currentPage="${pageModel.currenPage}"></page:pg>
			</html:form>

		</c:if>
	</body>
</html>




分页效果2种样式:
如下:
首页 上一页  下一页 1 2 3 4 5 6.... 下一页 末页

或者是只显示数字, 或者是文字


还有就是关于怎么使用查询类


在业务bean 里 这样写

继承basedao 或者是注入:

  
public PageModel<User> list(Integer currPage, Integer pageSize,String where) {
		QueryBuilder<User> qb = new HibernateQueryBuilder<User>(User.class)
				.addOrderBy(Order.asc("uid"));
		qb.like("uname", "%"+where+"%");//需要的条件都可以再这里点出来(如in like not in order by .....)
		return dao.find(currPage, pageSize, qb);
	}  



还忘记一点了:

就是basedao实现类里还引用了一个类,序列化,反序列化方法//主要是为了拷贝出一份QueryBuilder
一直没有好的方法来实现对象拷贝,希望大家指点下
  package org.ywq.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import org.ywq.common.QueryBuilder;

/**
 * @author ai5qiangshao E-mail:[email protected]
 * @version 创建时间:Aug 9, 2009 5:29:15 PM
 * @Package org.ywq.common.utils
 * @Description 类说明
 */
public class ObjectWriteorRead {
	public static void writeObject(Object o) {
		ObjectWriteorRead.writeObject(o, null);
	}

	public static void writeObject(Object o, OutputStream output) {
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		try {
			ObjectOutputStream out = new ObjectOutputStream(
					output == null ? byteOut : output);
			out.writeObject(o);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Object readObject(InputStream input) {
		Object o = null;
		try {
			ObjectInputStream in = new ObjectInputStream(input);
			o = in.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return o;
	}

}









你可能感兴趣的:(DAO,spring,Hibernate,jsp,笑话)