Skip to content

Instantly share code, notes, and snippets.

@thaniaclair
Last active December 17, 2015 05:49
Show Gist options
  • Save thaniaclair/5561122 to your computer and use it in GitHub Desktop.
Save thaniaclair/5561122 to your computer and use it in GitHub Desktop.
Cria várias cláusulas IN do SQL, de modo que não ocorram problemas de filtros em consultas quando maior que mil.
import java.util.List;
import org.apache.commons.lang3.StringUtils;
/**
* Cria várias cláusulas IN do SQL, de modo que não ocorram problemas de filtros em consultas,
* visto que quando um IN é inicializado com mais de mil valores, alguns SGBDs apresentam problemas
* para executar a consulta (exemplo: Oracle).
* @author thania.clair
*/
public class ClauseINBreaker {
private static final int DEFAULT_MAX_ITEMS_PER_CLAUSE = 500;
private String field;
private List<Integer> values;
private int maxBatch;
public ClauseINBreaker(String field, List<Integer> values) {
this.field = field;
this.values = values;
this.maxBatch = DEFAULT_MAX_ITEMS_PER_CLAUSE;
}
public ClauseINBreaker(String field, List<Integer> values, int maxBatch) {
this.field = field;
this.values = values;
this.maxBatch = maxBatch;
}
/**
* Constrói várias cláusulas IN, de acordo com o total de itens e o limite por lote configurado.
* Formato de retorno SQL: AND ( campo IN (1,2,3,4,5) OR campo IN (6,7,8,9,10) ... )
* @return código SQL com cláusulas IN.
*/
public StringBuilder execute() {
StringBuilder filterID = new StringBuilder(" AND ( ");
int size = values.size();
int batch = 0;
while (batch < size) {
int batchStart = batch;
int batchEnd = (batch + getMaxBatch());
if (batchEnd > size) batchEnd = size;
List<Integer> batchList = values.subList(batchStart, batchEnd);
String list = StringUtils.join(batchList, ",");
filterID.append(field).append(" IN (").append(list).append(") ");
batch = batchEnd;
if (batch < size) filterID.append(" OR ");
}
return filterID.append(" ) ");
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public List<Integer> getValues() {
return values;
}
public void setValues(List<Integer> values) {
this.values = values;
}
public int getMaxBatch() {
return maxBatch;
}
public void setMaxBatch(int maxBatch) {
this.maxBatch = maxBatch;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment