在项目中Hibernate中Criteria和Query查询,总是缺少不了一些列的判断等,无论数据类型是什么,这些是必须的,最终动态添加的也是的获取Criteria和Query组成的hql,于是公司兄弟将Criteria和Query进行了抽出封装,采用设计模式中Builder的模式将组成hql过程的判断进行封装组合,使大家在使用时减少了判断是否为空或者空字符串等,细细的相信其实这也是设计模式的一部分好处吧!
封装类如下:
public class DynamicQuery {
private StringBuilder hql = new StringBuilder();
public List<String> parameterNames = new ArrayList<String>();
public List<Object> parameterValues = new ArrayList<Object>();
public List<String> getParameterNames() {
return parameterNames;
}
public List<Object> getParameterValues() {
return parameterValues;
}
public DynamicQuery(String hql) {
this.hql.append(hql);
}
public DynamicQuery append(String hql) {
return append(hql, (String[]) null, (String[]) null);
}
public DynamicQuery appendIfTrue(String hql, boolean condition) {
if (condition) {
append(hql);
}
return this;
}
public DynamicQuery append(String hql, String[] names, Object[] values) {
this.hql.append(" ").append(hql);
if (names != null && names.length != 0) {
parameterNames.addAll(Arrays.asList(names));
}
if (values != null && values.length != 0) {
parameterValues.addAll(Arrays.asList(values));
}
return this;
}
public DynamicQuery append(String hql, List<String> names, List<Object> values){
this.hql.append(" ").append(hql);
if (names != null && !names.isEmpty()) {
parameterNames.addAll(names);
}
if (values != null && !values.isEmpty()) {
parameterValues.addAll(values);
}
return this;
}
public DynamicQuery append(String hql, String name, Object value) {
return append(hql, new String[]{name}, new Object[]{value});
}
public DynamicQuery appendIfNotNull(String hql, String name, Object value) {
if (value != null) {
return append(hql, name, value);
}
return this;
}
public DynamicQuery appendIfNotEmpty(String hql, String name, String value) {
if (StringUtils.isNotBlank(value)) {
return append(hql, name, StringUtils.trim(value));
}
return this;
}
public DynamicQuery appendIfNotEmpty(String hql, String name, Collection<?> collection) {
if (CollectionUtils.isNotEmpty(collection)) {
return append(hql, name, collection);
}
return this;
}
public DynamicQuery appendLikeIfNotEmpty(String hql, String name, String value) {
return appendLikeIfNotEmpty(hql, name, value, MatchMode.ANYWHERE);
}
public DynamicQuery appendLikeIfNotNull(String hql,String name, Long value){
if(null != value){
return append(hql,name,value);
}
return this;
}
public DynamicQuery appendLikeIfNotEmpty(String hql, String name, String value, MatchMode matchMode) {
if (StringUtils.isNotBlank(value)) {
return appendLike(hql, name, value, matchMode);
}
return this;
}
private DynamicQuery appendLike(String hql, String name, String value, MatchMode matchMode) {
//TODO check me for some days
String regex = "(?i)\\slike\\s+:" + name + "(?=(\\s|\\)|$))";
Matcher matcher = Pattern.compile(regex).matcher(hql);
if (matcher.find()) {
int appendStart = matcher.end();
String front = StringUtils.substring(hql, 0, appendStart);
String back = StringUtils.substring(hql, appendStart);
String likeHql = front + " escape \'^\' " + back;
String likeValue = StringUtils.trim(value).replaceAll("%", "^%").replaceAll("_", "^_");
return append(likeHql, name, matchMode.toMatchString(likeValue));
}
throw new IllegalArgumentException("Like hql[" + hql + "] is error format.");
}
public DynamicQuery appendIfNotEmpty(String hql, String name, Object[] values) {
return appendIfNotEmpty(hql, name, values != null ? Arrays.asList(values) : Collections.EMPTY_LIST);
}
public String getQueryString() {
return this.hql.toString();
}
/**
* Apply the given name parameter to the given Query object.
*
* @param query the Query object
* @param name the name of the parameter
* @param value the value of the parameter
*/
@SuppressWarnings("unchecked")
private void setParameter(Query query, String name, Object value) {
if (value instanceof Collection) {
query.setParameterList(name, (Collection) value);
} else if (value instanceof Object[]) {
query.setParameterList(name, (Object[]) value);
} else {
query.setParameter(name, value);
}
}
public Query build(Session session) {
Query query = session.createQuery(this.getQueryString());
if (parameterNames != null && !parameterNames.isEmpty()) {
for (int i = 0; i < parameterNames.size(); i++) {
this.setParameter(query, parameterNames.get(i), this.parameterValues.get(i));
}
}
return query;
}
}
使用代码如下:
/**
* 分页查询时使用
*
* @param <T>
* @param paginater
* @param searchCondition
* @return
*/
public <T> Paginater<T> paginate(Paginater<T> paginater, final ProductItemPriceCondition searchCondition) {
Sorter sorter = paginater.getSorter();
if (sorter.isEmpty()) {
sorter = new Sorter().asc("p.startDate");
}
LimitedList<T> limitedList = findByQuery(new QueryCreator() {
public Query createQuery(Session session) {
DynamicQuery dynamicQuery = new DynamicQuery("select distinct p from " + searchCondition.getForTypeName() + " p where (1 = 1) ");
dynamicQuery.appendIfNotNull(" and p.startDate<=:endDate ", "endDate", searchCondition.getEndDate());
dynamicQuery.appendIfNotNull(" and p.endDate>=:startDate ", "startDate", searchCondition.getStartDate());
dynamicQuery.appendIfNotNull("and p.productId=:productId ", "productId", searchCondition.getProductId());
return dynamicQuery.build(session);
}
}, paginater.getLimit(), sorter);
return paginater.fromLimitedList(limitedList);
}
代码实属完整,哈哈,以备后用!希望同学们拍砖哦 !!