com.github.antelopeframework.mybatis.criterion.CriteriaQueryTranslator Maven / Gradle / Ivy
package com.github.antelopeframework.mybatis.criterion;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
*
* @author yangzhi.yzh
*
*/
@Slf4j
@Getter
public class CriteriaQueryTranslator implements CriteriaQuery {
private final Criteria rootCriteria;
private final SqlSession sqlSession;
private final String queryCondition;
private final TypedValue[] queryParams;
public CriteriaQueryTranslator(SqlSession sqlSession, Criteria rootCriteria) {
this.sqlSession = sqlSession;
this.rootCriteria = rootCriteria;
this.queryCondition = buildQueryCondition();
this.queryParams = getQueryParameters();
}
private String buildQueryCondition() {
String whereCondition = getWhereCondition();
String orderBy = getOrderBy();
StringBuilder sqlBuffer = new StringBuilder();
if (StringUtils.isNotBlank(whereCondition)) {
sqlBuffer.append(" where ").append(whereCondition);
}
if (StringUtils.isNotBlank(orderBy)) {
sqlBuffer.append(" order by ").append(orderBy);
}
if (rootCriteria.getMaxResults() != 0) {
sqlBuffer.append(" limit " + rootCriteria.getMaxResults());
}
if (rootCriteria.getFirstResult() != 0) {
sqlBuffer.append(" offset " + rootCriteria.getFirstResult());
}
return sqlBuffer.toString();
}
private String getWhereCondition() {
StringBuilder condition = new StringBuilder(30);
Iterator criterionIterator = rootCriteria.iterateExpressionEntries();
while (criterionIterator.hasNext()) {
Criteria.CriterionEntry entry = criterionIterator.next();
String sqlString = entry.getCriterion().toSqlString(this);
condition.append(sqlString);
if (criterionIterator.hasNext()) {
condition.append(" and ");
}
}
return condition.toString();
}
private String getOrderBy() {
StringBuilder orderBy = new StringBuilder(30);
Iterator criterionIterator = rootCriteria.iterateOrderings();
while (criterionIterator.hasNext()) {
Criteria.OrderEntry oe = criterionIterator.next();
orderBy.append(oe.getOrder().toSqlString(this));
if (criterionIterator.hasNext()) {
orderBy.append(", ");
}
}
return orderBy.toString();
}
private TypedValue[] getQueryParameters() {
final List values = new ArrayList<>();
final Iterator iter = rootCriteria.iterateExpressionEntries();
while (iter.hasNext()) {
final Criteria.CriterionEntry ce = iter.next();
final TypedValue[] tv = ce.getCriterion().getTypedValues(this);
for (TypedValue aTv : tv) {
values.add(aTv);
}
}
return values.toArray(new TypedValue[0]);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy