BaseDao
package com.kaishengit.dao; import java.lang.reflect.ParameterizedType; import java.util.List; import javax.inject.Inject; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.transform.ResultTransformer; @SuppressWarnings("unchecked") public class BaseDao<T> { @Inject private SessionFactory sessionFactory; private Class<?> clazz; public BaseDao() { ParameterizedType baseDaoType = (ParameterizedType) this.getClass().getGenericSuperclass(); //BaseDao<User> clazz = (Class<?>) baseDaoType.getActualTypeArguments()[0]; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession() { return sessionFactory.getCurrentSession(); } /** * 添加或修改对象 * @param t */ public void save(T t) { getSession().save(t); } public void update(T t) { getSession().update(t); } /** * 删除一个对象 * @param t */ public void delete(T t) { getSession().delete(t); } /** * 根据ID删除对象 * @param id */ public void delete(int id) { getSession().delete(findById(id)); } /** * 根据ID查找对象 * @param id * @return */ public T findById(int id) { return (T)getSession().get(clazz, id); } /** * 获取所有对象 * @return */ public List<T> findAll() { return getCriteria().list(); } /** * 根据属性名称和值查找唯一的对象 * @param propertyName * @param value * @return */ public T findByPropertyForObject(String propertyName,Object value) { Criteria cri = getCriteria(); cri.add(Restrictions.eq(propertyName, value)); return (T) cri.uniqueResult(); } /** * 根据属性名称和值查找对象 * @param propertyName * @param value * @return */ public List<T> findByPropertyForList(String propertyName,Object value) { Criteria cri = getCriteria(); cri.add(Restrictions.eq(propertyName, value)); return cri.list(); } /** * 根据QueryFilter对象查找唯一对象 * @param filter * @return */ public T findByPropertyForObject(QueryFilter filter) { Criteria cri = getCriteria(); cri.add(createCriterion(filter)); return (T) cri.uniqueResult(); } /** * 根据QueryFilter集合(多条件)查找唯一对象 * @param filters * @return */ public T findByPropertyForObject(List<QueryFilter> filters) { Criteria cri = createCriterion(filters); return (T) cri.uniqueResult(); } /** * 根据QueryFilter集合(多条件)查找对象 * @param filters * @return */ public List<T> findByPropertyForList(List<QueryFilter> filters) { Criteria cri = createCriterion(filters); return cri.list(); } /** * 根据QueryFilter对象查找对象 * @param filter * @return */ public List<T> findByPropertyForList(QueryFilter filter) { Criteria cri = getCriteria(); cri.add(createCriterion(filter)); return cri.list(); } /** * 根据HQL查询唯一的对象 * @param hql * @param args * @return */ public T findByHqlForObject(String hql,Object...args) { Query query = getSession().createQuery(hql); for (int i = 0; i < args.length; i++) { query.setParameter(i, args[i]); } return (T) query.uniqueResult(); } /** * 根据HQL查询对象 * @param hql * @param args * @return */ public List<T> findByHqlForList(String hql,Object...args) { Query query = getSession().createQuery(hql); for (int i = 0; i < args.length; i++) { query.setParameter(i, args[i]); } return query.list(); } public List<T> findByPage(int start,int size) { Criteria cri = getCriteria(); cri.setFirstResult(start); cri.setMaxResults(size); return cri.list(); } public List<T> findByPage(int start,int size,QueryFilter filter) { Criteria cri = getCriteria(); cri.add(createCriterion(filter)); cri.setFirstResult(start); cri.setMaxResults(size); return cri.list(); } public Page<T> findByHqlPageNumber(String hql1, int page, int rows, Object...objects) { Query query=getSession().createQuery(hql1); for (int i = 0; i < objects.length; i++) { query.setParameter(i, objects[i]); } int count=query.list().size(); Page<T> page1 = new Page<T>(page,count,rows); query.setFirstResult(page1.getStartIndex()); query.setMaxResults(page1.getPageSize()); page1.setItems(query.list()); return page1; } public Page<T> findByHqlPageNumber(String hql,int pageNum,int pageSize) { Query query = getSession().createQuery(hql); int count=query.list().size(); Page<T> page = new Page<T>(pageNum,count,pageSize); query.setFirstResult(page.getStartIndex()); query.setMaxResults(page.getPageSize()); page.setItems(query.list()); return page; } public Page<T> findByPageNum(int pageNum,int pageSize) { Criteria cri = getCriteria(); @SuppressWarnings("static-access") ResultTransformer resultTransformer = cri.ROOT_ENTITY; cri.setProjection(Projections.rowCount()); Long count = (Long) cri.uniqueResult(); cri.setResultTransformer(resultTransformer); cri.setProjection(null); Page<T> page = new Page<T>(pageNum,count.intValue(),pageSize); cri.setFirstResult(page.getStartIndex()); cri.setMaxResults(page.getPageSize()); List<T> result = cri.list(); page.setItems(result); return page; } public Page<T> findByPageNum(int pageNum,int pageSize,QueryFilter filter) { Criteria cri = getCriteria(); cri.add(createCriterion(filter)); @SuppressWarnings("static-access") ResultTransformer resultTransformer = cri.ROOT_ENTITY; cri.setProjection(Projections.rowCount()); Long count = (Long) cri.uniqueResult(); cri.setResultTransformer(resultTransformer); cri.setProjection(null); Page<T> page = new Page<T>(pageNum,count.intValue(), pageSize); cri.setFirstResult(page.getStartIndex()); cri.setMaxResults(page.getPageSize()); List<T> result = cri.list(); page.setItems(result); return page; } public Page<T> findByPageNum(int pageNum,int pageSize,List<QueryFilter> filters) { Criteria cri = createCriterion(filters); @SuppressWarnings("static-access") ResultTransformer resultTransformer = cri.ROOT_ENTITY; cri.setProjection(Projections.rowCount()); Long count = (Long) cri.uniqueResult(); cri.setResultTransformer(resultTransformer); cri.setProjection(null); Page<T> page = new Page<T>(pageNum,count.intValue(),pageSize); cri.setFirstResult(page.getStartIndex()); cri.setMaxResults(page.getPageSize()); List<T> result = cri.list(); page.setItems(result); return page; } /** * @author YSC * @param counthql * @param hql * @param pageNum * @param rows * @return */ public Page<T> findByHqlAndPageForList(String counthql, StringBuilder hql, int pageNum, int rows,Object...args) { Query countQuery = getSession().createQuery(counthql); Query query = getSession().createQuery(hql.toString()); for (int i = 0; i < args.length; i++) { countQuery.setParameter(i, args[i]); query.setParameter(i, args[i]); } Long count = (Long) countQuery.uniqueResult(); Page<T> page = new Page<T>(pageNum,count.intValue(),rows); query.setFirstResult(page.getStartIndex()); query.setMaxResults(page.getPageSize()); List<T> result = query.list(); page.setItems(result); return page; } /** * @author gaolin * @param pageNum * @param pageSize * @param filters * @return */ public Page<T> findByPageNumAndSum(int pageNum,int pageSize,List<QueryFilter> filters) { Criteria cri = createCriterion(filters); @SuppressWarnings("static-access") ResultTransformer resultTransformer = cri.ROOT_ENTITY; cri.setProjection(Projections.rowCount()); Long count = (Long) cri.uniqueResult(); cri.setResultTransformer(resultTransformer); cri.setProjection(null); Page<T> page = new Page<T>(pageNum,count.intValue(),pageSize); cri.setFirstResult(page.getStartIndex()); cri.setMaxResults(page.getPageSize()); List<T> result = cri.list(); page.setItems(result); return page; } //help method private Criteria getCriteria() { return getSession().createCriteria(clazz); } public Criteria createCriterion(List<QueryFilter> filters) { Criteria cri = getCriteria(); if(filters != null && !filters.isEmpty()) { for(QueryFilter filter : filters) { cri.add(createCriterion(filter)); } } return cri; } private Criterion createCriterion(QueryFilter filter) { String propertyName = filter.getPropertyName(); Object value = filter.getValue(); String re = filter.getRe(); if(QueryFilter.EQ.equalsIgnoreCase(re)) { return Restrictions.eq(propertyName, value); } else if(QueryFilter.GE.equalsIgnoreCase(re)) { return Restrictions.ge(propertyName, value); } else if(QueryFilter.GT.equalsIgnoreCase(re)) { return Restrictions.gt(propertyName, value); } else if(QueryFilter.LE.equalsIgnoreCase(re)) { return Restrictions.le(propertyName, value); } else if(QueryFilter.LT.equalsIgnoreCase(re)) { return Restrictions.lt(propertyName, value); } else if(QueryFilter.LIKE.equalsIgnoreCase(re)) { return Restrictions.like(propertyName, value.toString(), MatchMode.ANYWHERE); } return null; } }
QueryFilter
package com.kaishengit.dao; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; public class QueryFilter { public static final String EQ = "eq"; //= public static final String GE = "ge"; //>= public static final String LE = "le"; //<= public static final String LT = "lt"; //< public static final String GT = "gt"; //> public static final String LIKE = "like"; // like private String propertyName; private Object value; private String re; public QueryFilter(String propertyName,String re,Object value) { this.propertyName = propertyName; this.value = value; this.re = re; } public QueryFilter() {} public QueryFilter(String propertyName,Object value) { this(propertyName,EQ,value); } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public String getRe() { return re; } public void setRe(String re) { this.re = re; } public static List<QueryFilter> builderQueryFilterByRequest( HttpServletRequest request) { List<QueryFilter> filters = new ArrayList<QueryFilter>(); Enumeration<String> e = request.getParameterNames(); while(e.hasMoreElements()) { String parmName = e.nextElement(); if(parmName.startsWith("Q_")) { if(parmName.indexOf("_") == parmName.lastIndexOf("_")) { throw new IllegalArgumentException("比较规则错误"); } else { String type = parmName.substring(parmName.indexOf("_")+1, parmName.lastIndexOf("_")); String propertyName = parmName.substring(parmName.lastIndexOf("_")+1); String value = request.getParameter(parmName); if(StringUtils.isNotEmpty(value)) { if(propertyName.contains("-")) { String propertyType = propertyName.substring(propertyName.indexOf("-")+1); propertyName = propertyName.substring(0,propertyName.indexOf("-")); Object v = value; if(propertyType.equalsIgnoreCase("i")) { v = Integer.parseInt(value); } else if(propertyType.equalsIgnoreCase("l")) { v = Long.parseLong(value); } else if(propertyType.equalsIgnoreCase("f")) { v = Float.parseFloat(value); } else if(propertyType.equalsIgnoreCase("d")) { v = Double.parseDouble(value); } else if(propertyType.equalsIgnoreCase("b")) { v = Boolean.parseBoolean(value); } QueryFilter filter = new QueryFilter(propertyName, type, v); filters.add(filter); } else { QueryFilter filter = new QueryFilter(propertyName, type, value); filters.add(filter); } } } } } return filters; } /** * @author YSC * @param request * @return */ @SuppressWarnings("unchecked") public static List<QueryFilter> builderQueryFilterByParams( HttpServletRequest request) { List<QueryFilter> filters = new ArrayList<QueryFilter>(); Enumeration<String> e = request.getParameterNames(); while(e.hasMoreElements()) { String parmName = e.nextElement(); if(parmName.startsWith("Q_")) { if(parmName.indexOf("_") == parmName.lastIndexOf("_")) { throw new IllegalArgumentException("比较规则错误"); } else { String type = parmName.substring(parmName.indexOf("_")+1, parmName.lastIndexOf("_")); String propertyName = parmName.substring(parmName.lastIndexOf("_")+1); String value = request.getParameter(parmName); if(StringUtils.isNotEmpty(value)) { if(propertyName.contains("$")) { String propertyType = propertyName.substring(propertyName.indexOf("$")+1); propertyName = propertyName.substring(0,propertyName.indexOf("$")); Object v = value; if(propertyType.equalsIgnoreCase("i")) { v = Integer.parseInt(value); } else if(propertyType.equalsIgnoreCase("l")) { v = Long.parseLong(value); } else if(propertyType.equalsIgnoreCase("f")) { v = Float.parseFloat(value); } else if(propertyType.equalsIgnoreCase("d")) { v = Double.parseDouble(value); } else if(propertyType.equalsIgnoreCase("b")) { v = Boolean.parseBoolean(value); } QueryFilter filter = new QueryFilter(propertyName, type, v); filters.add(filter); } else { QueryFilter filter = new QueryFilter(propertyName, type, value); filters.add(filter); } } } } } return filters; } public static List<QueryFilter> builderQueryFilterByRequestWithout( HttpServletRequest request) { List<QueryFilter> filters = new ArrayList<QueryFilter>(); Enumeration<String> e = request.getParameterNames(); while(e.hasMoreElements()) { String parmName = e.nextElement(); if(parmName.startsWith("Q_")) { if(parmName.indexOf("_") == parmName.lastIndexOf("_")) { throw new IllegalArgumentException("比较规则错误"); } else { String type = parmName.substring(parmName.indexOf("_")+1, parmName.lastIndexOf("_")); String propertyName = parmName.substring(parmName.lastIndexOf("_")+1); String value = request.getParameter(parmName); if(!("staffname".equals(propertyName)||"companyname".equals(propertyName))){ if(StringUtils.isNotEmpty(value)) { if(propertyName.contains("-")) { String propertyType = propertyName.substring(propertyName.indexOf("-")+1); propertyName = propertyName.substring(0,propertyName.indexOf("-")); Object v = value; if(propertyType.equalsIgnoreCase("i")) { v = Integer.parseInt(value); } else if(propertyType.equalsIgnoreCase("l")) { v = Long.parseLong(value); } else if(propertyType.equalsIgnoreCase("f")) { v = Float.parseFloat(value); } else if(propertyType.equalsIgnoreCase("d")) { v = Double.parseDouble(value); } else if(propertyType.equalsIgnoreCase("b")) { v = Boolean.parseBoolean(value); } QueryFilter filter = new QueryFilter(propertyName, type, v); filters.add(filter); } else { QueryFilter filter = new QueryFilter(propertyName, type, value); filters.add(filter); } } } } } } return filters; } /** * @author YSC * @param request * @return */ public static List<String> createHqlFromRequest(HttpServletRequest request) { @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); List<String> slist = new ArrayList<String>(); while(e.hasMoreElements()) { String parmName = e.nextElement(); if(parmName.startsWith("Q_")) { if(parmName.indexOf("_") == parmName.lastIndexOf("_")) { throw new IllegalArgumentException("比较规则错误"); } else { String type = parmName.substring(parmName.indexOf("_")+1, parmName.lastIndexOf("_")); String propertyName = parmName.substring(parmName.lastIndexOf("_")+1); String value = request.getParameter(parmName); if(StringUtils.isNotEmpty(value)) { Object v = value; if("EQ".equals(type)){ type = "="; }else if("LT".equals(type)){ type = "<"; }else if("LE".equals(type)){ type = "<="; }else if("GT".equals(type)){ type = ">"; }else if("GE".equals(type)){ type = ">="; }else if("LIKE".equals(type)){ type = "like"; } StringBuilder sb = new StringBuilder(); if(propertyName.contains("$")) { String propertyType = propertyName.substring(propertyName.indexOf("$")+1); propertyName = propertyName.substring(0,propertyName.indexOf("$")); sb.append(propertyName).append(" ").append(type); if(propertyType.equalsIgnoreCase("i")) { v = Integer.parseInt(value); sb.append(" "+v+" "); } else if(propertyType.equalsIgnoreCase("l")) { v = Long.parseLong(value); sb.append(" "+v+" "); } else if(propertyType.equalsIgnoreCase("f")) { v = Float.parseFloat(value); sb.append(" "+v+" "); } else if(propertyType.equalsIgnoreCase("d")) { v = Double.parseDouble(value); sb.append(" "+v+" "); } else if(propertyType.equalsIgnoreCase("b")) { v = Boolean.parseBoolean(value); sb.append(" "+v+" "); } }else{ sb.append(propertyName).append(" ").append(type); sb.append(" '"+v+"'"); } slist.add(sb.toString()); } } } } return slist; } }