It would be more logical to do less superfluous SQL.
int startWhere = builder.length();
if (type == EnumTypePrestation.OPTIQUE) {
builder.append(" and d.idDossier=p.id and d.statut=4");
}
if (...) {
builder.append(" and ...");
}
...
if (builder.length() > startWhere) {
builder.replace(startWhere, " and".length(), " where");
}
This code still is ugly. The attempt to be efficient using a StringBuilder is even error prone.
List<String> criteria = new ArrayList<>();
if (type == EnumTypePrestation.OPTIQUE) {
criteria.add("d.idDossier=p.id and d.statut=4");
}
...
if (!criteria.empty()) {
builder.append(criteria.stream()
.collect(Collectors.joining(" and ", " where ", " ");
// Or:
builder.append(criteria.stream()
.collect(Collectors.joining(") and (", " where (", ")");
}
joining
has here 3 parameters: separator, prefix and suffix.
There is one hard advise: do not try to make such code easier with this kind of tiny frameworks. This kind of database coding is very often done.
However the next programmer has to learn it, instead of an existing library. And the chance people program around it or the API will show up deficits, is large.
Better invest the time looking for an existing solution. You will save time on maintenance work (new features, difficult things with prepared statements, and so on).
The answer of rzwitserloot is to the point.