com.bixuebihui.jdbc.SqlSort Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of c-dbtools Show documentation
Show all versions of c-dbtools Show documentation
a fast small database connection pool and a active record flavor mini framework
/**
*
*/
package com.bixuebihui.jdbc;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* SqlSort class.
*
* @author xwx
* @version $Id: $Id
*/
public class SqlSort {
protected List sorts = new ArrayList<>();
/**
* addSort.
*
* @param property a {@link java.lang.String} object.
* @param order a {@link java.lang.String} object.
*/
public void addSort(String property, String order) {
sorts.add(new Sort(property, order));
}
public void addSortByIn(String property, Object[] order) {
sorts.add(new SortByIn(property, order));
}
/**
* Constructor for SqlSort.
*
* @param src a {@link SqlSort} object.
*/
public SqlSort(SqlSort src) {
//Sort为不变类,多个类引用不会因意外改变造不可预知问题
this.sorts.addAll(src.sorts);
}
/**
* Constructor for SqlSort.
*/
public SqlSort() {
}
/**
* toString.
*
* @return a {@link java.lang.String} object.
*/
@Override
public String toString() {
if (sorts.size() <= 0) {
return "";
}
StringBuilder criteria = new StringBuilder(" order by ");
for (Sortable sort : sorts) {
if(sort instanceof Sort) {
buildCriteria(criteria, ((Sort)sort).getProperty(), ((Sort)sort).getOrder());
}else if(sort instanceof SortByIn){
buildCriteria(criteria, ((SortByIn)sort).getProperty(), ((SortByIn)sort).getIds());
}
}
if (criteria.lastIndexOf(",") == criteria.length() - 1) {
return criteria.substring(0, criteria.length() - 1);
}
return criteria.toString();
}
private void buildCriteria(StringBuilder criteria, String property,
String order) {
if (order.equals(Sort.ASC)) {
criteria.append(property).append(" ").append(Sort.ASC).append(",");
} else if (order.equals(Sort.DESC)) {
criteria.append(property).append(" ").append(Sort.DESC).append(",");
}
}
private void buildCriteria(StringBuilder criteria, String property,
Object[] order) {
if(order ==null || order.length==0){return;}
criteria.append(" field( "+property+","+ StringUtils.repeat("?",",", order.length)+")");
}
public List