GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Groupby / Orderby support draft. · Xiermires/EntityMatcher@97b8c4f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src
    • main/java/org/entitymatcher
      • EntityMatcher.java
      • NumberConversion.java
    • test/java/org/entitymatcher
      • EntityMatcherTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/main/java/org/entitymatcher/EntityMatcher.java‎

Copy file name to clipboardExpand all lines: src/main/java/org/entitymatcher/EntityMatcher.java
+154-26Lines changed: 154 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -144,16 +144,21 @@ public static String toTable(String alias)
144144
return alias == null ? null : alias.substring(0, 1).toUpperCase().concat(alias.substring(1));
145145
}
146146

147+
// TODO: Cleanup
147148
public static class Builder<T> implements Observer
148149
{
149-
private Class<?> retType;
150+
private Class<T> retType;
150151
private boolean isNativeQuery = false;
151152
private final Stack<Capture> captures = new Stack<>();
152153
private final Set<String> tableNames = new LinkedHashSet<>();
153154
private final ParameterBinding params = new JpqlBinding();
155+
private final List<CapturedStatement> select = new ArrayList<>();
156+
private final List<CapturedStatement> groupBy = new ArrayList<>();
157+
private final List<CapturedStatement> orderBy = new ArrayList<>();
158+
private ORDER_BY order = null;
154159
private final List<CapturedStatement> statements = new ArrayList<>();
155-
private final List<CapturedStatement> customSelect = new ArrayList<>();
156160

161+
@SuppressWarnings("unchecked")
157162
Builder(T main, Object... others)
158163
{
159164
assert proxy2Class.containsKey(main.getClass()) //
@@ -166,7 +171,7 @@ public static class Builder<T> implements Observer
166171
tableNames.add(EntityMatcher.proxy2Class.get(main.getClass()).getSimpleName());
167172
Arrays.asList(others).forEach(o -> tableNames.add(EntityMatcher.proxy2Class.get(o.getClass()).getSimpleName()));
168173

169-
retType = EntityMatcher.proxy2Class.get(main.getClass());
174+
retType = (Class<T>) EntityMatcher.proxy2Class.get(main.getClass());
170175
}
171176

172177
/**
@@ -180,15 +185,56 @@ public static class Builder<T> implements Observer
180185
*/
181186
public Builder<T> select(Object... os)
182187
{
183-
customSelect.clear(); // doesn't allow incremental selects.
188+
select.clear(); // doesn't allow incremental selects.
184189
for (int i = 0; i < os.length; i++)
185190
{
186191
final Capture lastCapture = getLastCapture();
187192
assert lastCapture == null : "Builders are not thread safe.";
188193

189-
if (os[i] instanceof LhsRhsStatement) customSelect.add(new CapturedStatement(lastCapture, null,
194+
if (os[i] instanceof LhsRhsStatement) select.add(new CapturedStatement(lastCapture, null,
190195
(LhsRhsStatement<?>) os[i]));
191-
else customSelect.add(new CapturedStatement(lastCapture, null, null));
196+
else select.add(new CapturedStatement(lastCapture, null, null));
197+
}
198+
return this;
199+
}
200+
201+
public enum ORDER_BY
202+
{
203+
ASC, DESC
204+
};
205+
206+
public Builder<T> orderBy(Object... os)
207+
{
208+
return orderBy(ORDER_BY.ASC, os);
209+
}
210+
211+
public Builder<T> orderBy(ORDER_BY order, Object... os)
212+
{
213+
orderBy.clear(); // doesn't allow incremental orderBy's.
214+
this.order = order;
215+
for (int i = 0; i < os.length; i++)
216+
{
217+
final Capture lastCapture = getLastCapture();
218+
assert lastCapture == null : "Builders are not thread safe.";
219+
220+
if (os[i] instanceof LhsRhsStatement) orderBy.add(new CapturedStatement(lastCapture, null,
221+
(LhsRhsStatement<?>) os[i]));
222+
else orderBy.add(new CapturedStatement(lastCapture, null, null));
223+
}
224+
return this;
225+
}
226+
227+
public Builder<T> groupBy(Object... os)
228+
{
229+
groupBy.clear(); // doesn't allow incremental groupBy's.
230+
for (int i = 0; i < os.length; i++)
231+
{
232+
final Capture lastCapture = getLastCapture();
233+
assert lastCapture == null : "Builders are not thread safe.";
234+
235+
if (os[i] instanceof LhsRhsStatement) groupBy.add(new CapturedStatement(lastCapture, null,
236+
(LhsRhsStatement<?>) os[i]));
237+
else groupBy.add(new CapturedStatement(lastCapture, null, null));
192238
}
193239
return this;
194240
}
@@ -269,8 +315,7 @@ private String getColumnName(Field f)
269315
final Column c = f.getAnnotation(Column.class);
270316
return c == null || c.name().isEmpty() ? f.getName() : c.name();
271317
}
272-
else
273-
return f.getName();
318+
else return f.getName();
274319
}
275320

276321
Capture getLastCapture()
@@ -315,6 +360,9 @@ public String toString()
315360

316361
public PreparedQuery<T> build()
317362
{
363+
if (isNativeQuery)
364+
return build(retType);
365+
318366
return new PreparedQuery<T>()
319367
{
320368
@Override
@@ -347,16 +395,19 @@ public String toString()
347395
};
348396
}
349397

398+
@SuppressWarnings("unchecked")
350399
public <E> PreparedQuery<E> build(Class<E> clazz)
351400
{
401+
if (clazz.equals(retType) && !isNativeQuery)
402+
return (PreparedQuery<E>) build();
403+
352404
return new PreparedQuery<E>()
353405
{
354-
@SuppressWarnings("unchecked")
355406
private Function<Object[], E> copyProperties = os ->
356407
{
357408
try
358409
{
359-
assert os.length == customSelect.size() : "Request / response column size mismatch.";
410+
assert os.length == select.size() : "Request / response column size mismatch.";
360411

361412
// If length == 1, it could be two options:
362413
// 1. List<Integer> is = ...build(Integer.class).getMatching(em)
@@ -377,13 +428,37 @@ else if (clazz.isAssignableFrom(o.getClass()))
377428
}
378429

379430
final E e = clazz.newInstance();
380-
for (int i = 0; i < os.length; i++)
431+
if (select.isEmpty())
381432
{
382-
final CapturedStatement c = customSelect.get(i);
383-
final Class<?> paramType = c.lhs.method.getReturnType();
384-
final String setterName = c.lhs.method.getName().replaceFirst("(is|get)", "set");
385-
final Method setterMethod = clazz.getMethod(setterName, paramType);
386-
setterMethod.invoke(e, os[i]);
433+
int i = 0;
434+
// FIXME review all this.
435+
for (Field f : clazz.getDeclaredFields())
436+
{
437+
if (f.isAnnotationPresent(Transient.class))
438+
continue;
439+
440+
if (os[i] == null)
441+
{
442+
i++;
443+
continue;
444+
}
445+
446+
final int rank = NumberConversion.getRank(f.getType());
447+
final Object o = rank >= 0 ? NumberConversion.convert(os[i], rank) : os[i];
448+
f.set(e, o);
449+
i++;
450+
}
451+
}
452+
else
453+
{
454+
for (int i = 0; i < os.length; i++)
455+
{
456+
final CapturedStatement c = select.get(i);
457+
final Class<?> paramType = c.lhs.method.getReturnType();
458+
final String setterName = c.lhs.method.getName().replaceFirst("(is|get)", "set");
459+
final Method setterMethod = clazz.getMethod(setterName, paramType);
460+
setterMethod.invoke(e, os[i]);
461+
}
387462
}
388463
return e;
389464
}
@@ -409,7 +484,6 @@ public E getSingleMatching(EntityManager em)
409484
}
410485

411486
@Override
412-
@SuppressWarnings("unchecked")
413487
public List<E> getMatching(EntityManager em)
414488
{
415489
return Lists.transform(createQuery(em, isNativeQuery).getResultList(), copyProperties);
@@ -444,15 +518,60 @@ public int compare(CapturedStatement o1, CapturedStatement o2)
444518

445519
final Set<String> unaliasedTables = new LinkedHashSet<>(Builder.this.tableNames);
446520
final StringBuilder fromClause = new StringBuilder().append(" FROM ");
447-
final String select = composeSelect(fromClause, unaliasedTables);
448-
521+
final String select = appendSelectAndFrom(fromClause, unaliasedTables);
449522
if (statements.isEmpty())
450523
{
451-
return new StringBuilder(select).append(removeLastComma(fromClause)).toString();
524+
return new StringBuilder(select).append(removeLastComma(fromClause)).append(getGroupByClause()).append(getOrderByClause()).toString();
452525
}
453526

454527
final StringBuilder whereClause = new StringBuilder().append(" WHERE ");
528+
appendFromAndWhere(unaliasedTables, fromClause, whereClause);
529+
530+
final StringBuilder groupByClause = getGroupByClause();
531+
final StringBuilder orderByClause = getOrderByClause();
532+
533+
return new StringBuilder(select).append(fromClause).append(whereClause).append(groupByClause).append(orderByClause)
534+
.toString();
535+
}
536+
537+
private StringBuilder getOrderByClause()
538+
{
539+
final StringBuilder orderByClause = new StringBuilder();
540+
if (!orderBy.isEmpty())
541+
{
542+
orderByClause.append(" ORDER BY ");
543+
for (Iterator<CapturedStatement> it = orderBy.iterator(); it.hasNext();)
544+
{
545+
final CapturedStatement next = it.next();
546+
orderByClause.append(toAlias(getTableName(next.lhs))).append(".").append(getColumnName(next.lhs));
547+
if (it.hasNext())
548+
orderByClause.append(", ");
549+
}
550+
orderByClause.append(" ").append(order.name());
551+
}
552+
return orderByClause;
553+
}
554+
555+
private StringBuilder getGroupByClause()
556+
{
557+
final StringBuilder groupByClause = new StringBuilder();
558+
if (!groupBy.isEmpty())
559+
{
560+
groupByClause.append(" GROUP BY ");
561+
for (Iterator<CapturedStatement> it = groupBy.iterator(); it.hasNext();)
562+
{
563+
final CapturedStatement next = it.next();
564+
groupByClause.append(toAlias(getTableName(next.lhs))).append(".").append(getColumnName(next.lhs));
565+
if (it.hasNext())
566+
groupByClause.append(", ");
567+
}
568+
}
569+
return groupByClause;
570+
}
455571

572+
private void appendFromAndWhere(final Set<String> unaliasedTables, final StringBuilder fromClause,
573+
final StringBuilder whereClause)
574+
{
456575
final Iterator<CapturedStatement> it = statements.iterator();
457576
while (it.hasNext())
458577
{
@@ -495,7 +614,6 @@ public int compare(CapturedStatement o1, CapturedStatement o2)
495614
}
496615

497616
removeLastComma(fromClause);
498-
return new StringBuilder(select).append(fromClause).append(whereClause).toString();
499617
}
500618

501619
// It is actually easier to remove a known last comma, that to handle all unknowns while
@@ -505,11 +623,21 @@ private StringBuilder removeLastComma(final StringBuilder fromClause)
505623
return fromClause.replace(fromClause.length() - 2, fromClause.length(), "");
506624
}
507625

508-
private String composeSelect(StringBuilder fromClause, Set<String> unaliasedTables)
626+
private String appendSelectAndFrom(StringBuilder fromClause, Set<String> unaliasedTables)
509627
{
510-
return !customSelect.isEmpty() ? createCustomSelect(fromClause, unaliasedTables)
511-
: isNativeQuery ? createNativeSelect(fromClause, unaliasedTables) : "SELECT ".concat(toAlias(retType
512-
.getSimpleName()));
628+
return !select.isEmpty() ? createCustomSelect(fromClause, unaliasedTables)
629+
: isNativeQuery ? createNativeSelect(fromClause, unaliasedTables) : createSimpleSelect(fromClause,
630+
unaliasedTables);
631+
}
632+
633+
private String createSimpleSelect(StringBuilder fromClause, Set<String> unaliasedTables)
634+
{
635+
final String tableName = getTableName(retType);
636+
final String tableAlias = toAlias(tableName);
637+
unaliasedTables.remove(tableName);
638+
639+
fromClause.append(tableName).append(" ").append(tableAlias).append(", ");
640+
return "SELECT ".concat(tableAlias);
513641
}
514642

515643
private String createNativeSelect(StringBuilder fromClause, Set<String> unaliasedTables)
@@ -539,7 +667,7 @@ private String createNativeSelect(StringBuilder fromClause, Set<String> unaliase
539667
private String createCustomSelect(StringBuilder fromClause, Set<String> unaliasedTables)
540668
{
541669
final StringBuilder sb = new StringBuilder("SELECT ");
542-
for (Iterator<CapturedStatement> it = customSelect.iterator(); it.hasNext();)
670+
for (Iterator<CapturedStatement> it = select.iterator(); it.hasNext();)
543671
{
544672
final CapturedStatement next = it.next();
545673
final String tableName = getTableName(next.lhs);
Collapse file

‎src/main/java/org/entitymatcher/NumberConversion.java‎

Copy file name to clipboard
+90Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package org.entitymatcher;
2+
3+
import java.math.BigInteger;
4+
5+
class NumberConversion
6+
{
7+
private static final int BYTE = 0;
8+
private static final int SHORT = 1;
9+
private static final int INT = 2;
10+
private static final int LONG = 3;
11+
private static final int FLOAT = 4;
12+
private static final int DOUBLE = 5;
13+
private static final int BIGINTEGER = 6;
14+
15+
/**
16+
* Returns the numeric wrapper type ranked from [0 to 5] corresponding to the numeric wrapper sorted by min/max representable
17+
* numbers.
18+
* <p>
19+
* Returns {@link Double#NaN} if class is not a numeric wrapper.
20+
*/
21+
public static int getRank(Class<?> wrapper)
22+
{
23+
if (Integer.class == wrapper || int.class == wrapper)
24+
{
25+
return INT;
26+
}
27+
else if (Double.class == wrapper || double.class == wrapper)
28+
{
29+
return DOUBLE;
30+
}
31+
else if (Float.class == wrapper || float.class == wrapper)
32+
{
33+
return FLOAT;
34+
}
35+
else if (Long.class == wrapper || long.class == wrapper)
36+
{
37+
return LONG;
38+
}
39+
else if (Short.class == wrapper || short.class == wrapper)
40+
{
41+
return SHORT;
42+
}
43+
else if (Byte.class == wrapper || byte.class == wrapper)
44+
{
45+
return BYTE;
46+
}
47+
else if (BigInteger.class == wrapper)
48+
{
49+
return BIGINTEGER;
50+
}
51+
return -1; // no convertible number.
52+
}
53+
54+
public static Number convert(Object n, int rank)
55+
{
56+
if (n instanceof Number)
57+
{
58+
if (INT == rank)
59+
{
60+
return ((Number) n).intValue();
61+
}
62+
else if (DOUBLE == rank)
63+
{
64+
return ((Number) n).doubleValue();
65+
}
66+
else if (FLOAT == rank)
67+
{
68+
return ((Number) n).floatValue();
69+
}
70+
else if (LONG == rank)
71+
{
72+
return ((Number) n).longValue();
73+
}
74+
else if (SHORT == rank)
75+
{
76+
return ((Number) n).shortValue();
77+
}
78+
else if (BYTE == rank)
79+
{
80+
return ((Number) n).byteValue();
81+
}
82+
else if (BIGINTEGER == rank)
83+
{
84+
return new BigInteger(n.toString());
85+
}
86+
}
87+
return null;
88+
}
89+
}
90+

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.