Skip to content

Instantly share code, notes, and snippets.

@Tzrlk
Last active December 23, 2015 09:49
Show Gist options
  • Save Tzrlk/6617248 to your computer and use it in GitHub Desktop.
Save Tzrlk/6617248 to your computer and use it in GitHub Desktop.
An idea I had for a query proxy pattern.
public abstract class EbeanQuery<ResultType>
extends Query<ResultType> {
protected ExpressionList<ResultType> expressionList;
public ResultType getResult() {
return expressionList.findUnique();
}
public ResultType getFirstResult() {
return expressionList
.setMaxRows(1)
.findUnique();
}
public List<ResultType> getResultList() {
return expressionList.findList();
}
public PaginatedResultList<ResultType> getPaginatedResultList(int max, int start) {
// Start working on the row count of the un-paginated query expression.
FutureRowCount<ResultType> rowCount = expressionList.findFutureRowCount();
// Paginate the query expression and retrieve the results.
List<ResultType> results = expressionList
.setMaxRows(max)
.setFirstRow(start)
.findList();
// Wrap both bits of information in a useful package.
return new PaginatedResultList(results, total.get());
}
}
public abstract class EbeanQueryProvider<QueryType extends EbeanQuery, ResultType>
implements QueryProvider<QueryType, ResultType> {
protected EbeanServer ebean;
protected ExpressionList<ResultType> getExpression(Class<ResultType> clazz) {
return ebean.find(clazz).where();
}
}
/**
* Not so sure on this one. While it would be nice to have a standardised way of defining filters, Java doesn't deal
* with Maps nearly as well as Groovy, making it a bad choice for easily passing arguments. The alternate way around
* it would be to instantiate a filter with the specified arguments, and then blindly apply it to the expression.
* Since each filter would only hold state for its arguments, you could re-use them.
*/
public interface ExpressionFilter<ExpressionType> {
public ExpressionType filter(ExpressionType expression);
public ExpressionType filter(ExpressionType expression, Map<String, Object> params);
}
public class PaginatedResultList<ResultType> {
private final List<ResultType> results;
private final int total;
public PaginatedResultList(List<ResultType> results, int total) {
this.results = results;
this.total = total;
}
public List<ResultType> getResults() {
return this.results;
}
public int getTotal() {
return this.total;
}
}
public interface Query<ResultType> {
public ResultType getResult();
public ResultType getFirstResult();
public List<ResultType> getResultList();
public PaginatedResultList<ResultType> getPaginatedResultList(int max, int start);
}
public interface QueryProvider<QueryType extends Query<ResultType>, ResultType> {
public QueryType getQuery();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment