com.github.napp.database.impl.SelectQuery Maven / Gradle / Ivy
/**
*
*/
package com.github.napp.database.impl;
import static com.github.napp.util.UClose.CLOSE_RESULT_SET;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.github.napp.database.IEntity;
import com.github.napp.database.ISelectQuery;
import com.github.napp.util.UString;
/**
* @author Alexandru Bledea
* @since Sep 21, 2013
*/
class SelectQuery extends WhereQuery implements ISelectQuery {
private final PreparedStatementEvaluator> RESULTSET_RESULT = new PreparedStatementEvaluator>() {
@Override
public List evaluate(PreparedStatement object) throws Exception {
ResultSet rs = null;
try {
rs = object.executeQuery();
return createList(rs);
} finally {
CLOSE_RESULT_SET.evaluate(rs);
}
};
};
private int limitStart;
private int limitMax = 15;
private boolean asc;
private String sortColumn;
/**
* @param dao
* @param entityMapper
*/
SelectQuery(DAO dao) {
super(dao, "SELECT * FROM ");
}
/* (non-Javadoc)
* @see com.github.napp.database.impl.WhereQuery#addToQuery(java.lang.StringBuilder)
*/
@Override
protected void addToQuery(StringBuilder sb) {
super.addToQuery(sb);
addOrder(sb);
addLimit(sb);
}
/**
* @param sb
*/
private void addOrder(StringBuilder sb){
if (!UString.empty(sortColumn)) {
sb.append(" ORDER BY ").append(sortColumn).append(" ").append(asc ? "ASC" : "DESC");
}
}
/**
* @param sb
*/
private void addLimit(StringBuilder sb) {
sb.append(" LIMIT ").append(limitStart).append(", ").append(limitMax);
}
/* (non-Javadoc)
* @see com.github.napp.database.IQuery#executeQuery()
*/
@Override
public List executeQuery() {
return execute(RESULTSET_RESULT);
}
/**
* @param executeQuery
* @return
* @throws Exception
*/
private List createList(ResultSet executeQuery) throws Exception {
List list = new ArrayList();
int columnCount = executeQuery.getMetaData().getColumnCount();
EntityMapper entityMapper = dao.getEntityMapper();
while (executeQuery.next()) {
list.add(entityMapper.mapEntity(executeQuery, columnCount));
}
return list;
}
/* (non-Javadoc)
* @see com.github.napp.database.ISelectQuery#setLimit(int)
*/
@Override
public void setLimit(int max) {
setLimit(0, max);
}
/* (non-Javadoc)
* @see com.github.napp.database.ISelectQuery#setLimit(int, int)
*/
@Override
public void setLimit(int start, int max) {
this.limitStart = start;
this.limitMax = max;
}
/* (non-Javadoc)
* @see com.github.napp.database.ISelectQuery#setOrderBy(java.lang.String, boolean)
*/
@Override
public void setOrderBy(String property, boolean asc) {
sortColumn = property;
this.asc = asc;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy