package cn.itcast.core.util; import java.util.ArrayList; import java.util.List; public class QueryHelper { //from子句 private String fromClause = ""; //where子句 private String whereClause = ""; //order by子句 private String orderByClause = ""; private List<Object> parameters; //排序递次 public static String ORDER_BY_DESC = "DESC";//降序 public static String ORDER_BY_ASC = "ASC";//升序 /** * 组织from 子句 * @param clazz 实体类 * @param alias 实体类对应的别号 */ public QueryHelper(Class clazz, String alias){ fromClause = "FROM " + clazz.getSimpleName() + " " + alias; } /** * 组织where子句 * @param condition 查询前提语句;例如:i.title like ? * @param params 查询前提语句中?对应的查询前提值;例如: %题目% */ public void addCondition(String condition, Object... params){ if (whereClause.length() > 1) {//非第一个查询前提 whereClause += " AND " + condition; } else {//第一个查询前提 whereClause += " WHERE " + condition; } //设置查询前提值到查询前提值鸠合中 if(parameters == null){ parameters = new ArrayList<Object>(); } if(params != null){ for(Object param: params){ parameters.add(param); } } } /** * 组织order by子句 * @param property 排序属性,如:i.createTime * @param order 排序递次,如:DESC 或者 ASC */ public void addOrderByProperty(String property, String order){ if (orderByClause.length() > 1) {//非第一个排序属性 orderByClause += "," + property + " " + order; } else {//第一个排序属性 orderByClause = " ORDER BY " + property + " " + order; } } //查询hql语句 public String getQueryListHql(){ return fromClause + whereClause + orderByClause; } //查询统计数的hql语句 public String getQueryCountHql(){ return "SELECT COUNT(*) " + fromClause + whereClause; } //查询hql语句中?对应的查询前提值鸠合 public List<Object> getParameters(){ return parameters; } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/11701.html