Skip to content

Commit c101c93

Browse files
committed
Implemented groupBy and having
1 parent 2e56307 commit c101c93

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/main/java/org/javawebstack/orm/query/Query.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import java.util.HashMap;
1515
import java.util.List;
1616
import java.util.Map;
17+
import java.util.function.Consumer;
1718
import java.util.function.Function;
1819
import java.util.stream.Stream;
1920

@@ -27,6 +28,8 @@ public class Query<T extends Model> {
2728
private QueryOrderBy order;
2829
private boolean withDeleted = false;
2930
private final List<QueryWith> withs = new ArrayList<>();
31+
private final List<QueryColumn> groupBy = new ArrayList<>();
32+
private QueryGroup<T> having;
3033

3134
public Query(Class<T> model) {
3235
this(Repo.get(model), model);
@@ -51,6 +54,14 @@ public List<QueryWith> getWiths() {
5154
return withs;
5255
}
5356

57+
public List<QueryColumn> getGroupBy() {
58+
return groupBy;
59+
}
60+
61+
public QueryGroup<T> getHaving() {
62+
return having;
63+
}
64+
5465
public Integer getLimit() {
5566
return limit;
5667
}
@@ -278,6 +289,22 @@ public Query<T> orWhereNotIn(Object left, Object... values) {
278289
return this;
279290
}
280291

292+
public Query<T> groupBy(String column) {
293+
groupBy.add(new QueryColumn(column));
294+
return this;
295+
}
296+
297+
public Query<T> groupBy(QueryColumn column) {
298+
groupBy.add(column);
299+
return this;
300+
}
301+
302+
public Query<T> having(Consumer<QueryGroup<T>> consumer) {
303+
having = new QueryGroup<>();
304+
consumer.accept(having);
305+
return this;
306+
}
307+
281308
public Query<T> accessible(Object accessor) {
282309
return repo.accessible(this, accessor);
283310
}

src/main/java/org/javawebstack/orm/wrapper/builder/MySQLQueryStringBuilder.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,18 @@ public SQLQueryString buildQuery(Query<?> query, boolean count) {
5050
parameters.addAll(qs.getParameters());
5151
}
5252

53+
if(query.getGroupBy().size() > 0) {
54+
sb.append(" GROUP BY ");
55+
sb.append(query.getGroupBy().stream().map(c -> c.toString(repo.getInfo())).collect(Collectors.joining(",")));
56+
}
57+
58+
if(query.getHaving() != null) {
59+
sb.append(" HAVING ");
60+
SQLQueryString group = convertGroup(repo.getInfo(), query.getHaving());
61+
sb.append(group.getQuery());
62+
parameters.addAll(group.getParameters());
63+
}
64+
5365
QueryOrderBy orderBy = query.getOrder();
5466
if (!orderBy.isEmpty()) {
5567
sb.append(" ORDER BY ")

0 commit comments

Comments
 (0)