Last active
February 26, 2018 15:54
-
-
Save dileeph/0df4fab9c99c83d80565fd3418fdf5a2 to your computer and use it in GitHub Desktop.
build query using java 8 features
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.my.crawler; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.function.Supplier; | |
public class QueryBuilder { | |
private Map<String, Object> parameterMap = new HashMap<>(); | |
private StringBuilder querySBuilder; | |
public QueryBuilder() { | |
querySBuilder = new StringBuilder(); | |
} | |
public QueryBuilder(String initialSQL) { | |
querySBuilder = new StringBuilder(initialSQL); | |
} | |
/** | |
* addQuery(" and user = :username", "username", "John"); | |
*/ | |
public <R> QueryBuilder addQuery(String query, String parameterName, R parameterValue) { | |
querySBuilder.append(query); | |
parameterMap.put(parameterName, parameterValue); | |
return this; | |
} | |
/** | |
* String userName = "John"; | |
* addQuery(" and user = :username", "username", () -> userName.toUpperCase()); | |
*/ | |
public <T> QueryBuilder addQuery(String query, String parameterName, Supplier<T> parameterValue) { | |
querySBuilder.append(query); | |
parameterMap.put(parameterName, parameterValue.get()); | |
return this; | |
} | |
/** | |
* String userName = "John"; | |
* addQuery(" and user = :username", "username", () -> userName.toUpperCase(), () -> userName != null && !userName.equals("baduser")); | |
*/ | |
public <T> QueryBuilder addQuery(String query, String parameterName, Supplier<T> parameterValue, | |
Supplier<Boolean> successCondition) { | |
if (successCondition.get()) { | |
querySBuilder.append(query); | |
parameterMap.put(parameterName, parameterValue.get()); | |
} | |
return this; | |
} | |
/** | |
* String userName = "John"; | |
* addQuery(" and user = :username", "username", () -> userName.toUpperCase(), | |
* () -> userName != null && !userName.equals("baduser"), | |
* () -> new IOException()); | |
*/ | |
public <T> QueryBuilder addQuery(String query, String parameterName, Supplier<T> parameterValue, | |
Supplier<Boolean> successCondition, Supplier<Exception> failureException) throws Exception { | |
if (successCondition.get()) { | |
querySBuilder.append(query); | |
parameterMap.put(parameterName, parameterValue.get()); | |
} else { | |
throw failureException.get(); | |
} | |
return this; | |
} | |
public Query build() { | |
return new Query(querySBuilder.toString(), parameterMap); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment