package cn.itcast.oa.util;
import java.util.ArrayList;
import java.util.List;
import cn.itcast.oa.base.DaoSupport;
import cn.itcast.oa.domain.PageBean;
import com.opensymphony.xwork2.ActionContext;
/**
* 用于辅助拼接HQL语句_工具
*
* @author
* @version V1.0
*/
@SuppressWarnings({ "rawtypes" })
public class QueryHelper {
private String fromClause;// From子句
private String whereClause = "";// Where子句
private String orderByClause = "";// OrderBy子句
private List<Object> parameters = new ArrayList<Object>();// 参数列表
/**
* 生成From子句
*
* @param clazz
* @param alias
* 别名
*/
public QueryHelper(Class clazz, String alias) {
fromClause = " from " + clazz.getSimpleName() + " " + alias;// from User u
}
/**
* 拼接Where子句
*
* @param condition
* @param params
*/
public QueryHelper addCondition(String condition, Object... params) {
// 拼接
if (whereClause.length() == 0) {
whereClause = " where " + condition;// from User u where ?
} else {
whereClause += " and " + condition;// from User u where ?,and ?
}
// 参数
if (params != null) {
for (Object obj : params) {
parameters.add(obj);
}
}
return this;
}
/**
* 如果第一个参数为true,则拼接Where子句
*
* @param append
* @param condition
* @param params
*/
public QueryHelper addCondition(boolean append, String condition, Object... params) {
if (append) {
addCondition(condition, params);
}
return this;
}
/**
* 拼接OrderBy子句
*
* @param propertyName
* 参于排序的属性名
* @param asc
* true表示升序(1,2,3),false表示降序(3,2,1)
*/
public QueryHelper addOrderProperty(String propertyName, boolean asc) {
if (orderByClause.length() == 0) {
orderByClause = " Order by " + propertyName + (asc ? " asc " : " desc ");// from User u where ? order by ? asc/desc
} else {
orderByClause += " , " + propertyName + (asc ? " asc " : " desc ");// from User u where ? order by ? asc/desc,? asc/desc
}
return this;
}
/**
* 如果第一个参数为true,则拼接OrderBy子句
*
* @param append
* @param propertyName
* @param asc
*/
public QueryHelper addOrderProperty(boolean append, String propertyName, boolean asc) {
if (append) {
addOrderProperty(propertyName, asc);
}
return this;
}
/**
* 获取生成用于查询数据列表的HQL语句
*
* @return
*/
public String getListQueryHql() {
return fromClause + whereClause + orderByClause;
}
/**
* 获取生成用于查询总记录数的HQL语句
*
* @return
*/
public String getCountQueryHql() {
return " select count(*) " + fromClause + whereClause;
}
/**
* 获取HQL中的参数值列表
*
* @return
*/
public List<Object> getParameters() {
return parameters;
}
/**
* 查询分页信息,并放到值栈栈顶
* @param service
* @param pageNum
* @param pageSize
*/
public void preparePageBean(DaoSupport<?> service,int pageNum, int pageSize) {
PageBean pageBean = service.getPageBean(pageNum, pageSize, this);
ActionContext.getContext().getValueStack().push(pageBean);
}
}
用于辅助拼接HQL语句_工具
最新推荐文章于 2021-05-23 06:53:20 发布