Created
January 15, 2019 17:01
-
-
Save srcmaxim/d77492138d939766afbc406e0b2cca72 to your computer and use it in GitHub Desktop.
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
class SQLPredicate<T> { | |
private final Predicate<T> t; | |
private final String sql; | |
SQLPredicate(Predicate<T> t, String name) { | |
this.t = t; | |
this.sql = name; | |
} | |
static <T> SQLPredicate<T> of(Predicate<T> t, String sql) { | |
return new SQLPredicate<T>(t, sql); | |
} | |
String getSql() { | |
return sql; | |
} | |
boolean test(T t) { | |
return this.t.test(t); | |
} | |
SQLPredicate<T> and(SQLPredicate<? super T> other) { | |
return new SQLPredicate<>((t) -> this.test(t) && other.test(t), "(" + this.sql + " AND " + other.sql + ")"); | |
} | |
SQLPredicate<T> negate() { | |
return new SQLPredicate<>((t) -> !this.test(t), "NOT " + this.sql); | |
} | |
SQLPredicate<T> or(SQLPredicate<? super T> other) { | |
return new SQLPredicate<>((t) -> this.test(t) || other.test(t), "(" + this.sql + " OR " + other.sql + ")"); | |
} | |
} | |
class Entity { | |
public String name; | |
public String address; | |
public Integer year; | |
public Entity(String name, String address, Integer year) { | |
this.name = name; | |
this.address = address; | |
this.year = year; | |
} | |
} | |
SQLPredicate<Entity> hasName = of(e -> e.name != null, "name = :name"); | |
SQLPredicate<Entity> hasAddress = of(e -> e.address != null, "address = :address"); | |
SQLPredicate<Entity> hasYear = of(e -> e.year != null, "year = :year"); | |
SQLPredicate<Entity> hasAll = of( | |
e -> e.year != null & e.address != null & e.name != null, | |
"year = :year and year = :year and year = :year"); | |
SQLPredicate<Entity> hasNameOrAddress = hasName.or(hasAddress); | |
SQLPredicate<Entity> hasYearAndHasNameOrAddress = hasYear.and(hasNameOrAddress); | |
hasYearAndHasNameOrAddress.getSql(); | |
hasYearAndHasNameOrAddress.test(new Entity(null, "addr", 1995)); | |
hasYearAndHasNameOrAddress.test(new Entity(null, "addr", null)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment