-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEntityQuery.java
More file actions
411 lines (356 loc) · 12.9 KB
/
EntityQuery.java
File metadata and controls
411 lines (356 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package com.github.collinalpert.java2db.queries;
import com.github.collinalpert.expressions.expression.LambdaExpression;
import com.github.collinalpert.java2db.annotations.ForeignKeyEntity;
import com.github.collinalpert.java2db.database.*;
import com.github.collinalpert.java2db.entities.BaseEntity;
import com.github.collinalpert.java2db.mappers.*;
import com.github.collinalpert.java2db.modules.TableModule;
import com.github.collinalpert.java2db.queries.builder.*;
import com.github.collinalpert.java2db.queries.ordering.OrderTypes;
import com.github.collinalpert.java2db.utilities.IoC;
import com.github.collinalpert.lambda2sql.functions.*;
import java.lang.reflect.Array;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* A class representing a DQL statement with different options, including where clauses, order by clauses and limits.
* It also automatically joins foreign keys so the corresponding entities (marked with the {@link ForeignKeyEntity} attribute) can be filled.
*
* @author Collin Alpert
*/
public class EntityQuery<E extends BaseEntity> implements Queryable<E> {
private static final TableModule tableModule = TableModule.getInstance();
protected final TransactionManager transactionManager;
protected final IQueryBuilder<E> queryBuilder;
protected final QueryParameters<E> queryParameters;
private final Class<E> type;
private final Mappable<E> mapper;
/**
* Constructor for creating a DQL statement for a given entity.
* This constructor should not be used directly, but through the DQL methods defined in the {@link com.github.collinalpert.java2db.services.BaseService}.
*
* @param type The entity to query.
*/
public EntityQuery(Class<E> type, TransactionManager transactionManager) {
this.type = type;
this.transactionManager = transactionManager;
this.queryParameters = new QueryParameters<>();
this.mapper = IoC.resolveMapper(type, new EntityMapper<>(type));
this.queryBuilder = new EntityQueryBuilder<>(type);
}
//region Where
/**
* Sets or appends a WHERE clause for the DQL statement.
*
* @param predicate The predicate describing the WHERE clause.
* @return This {@link EntityQuery} object, now with an (appended) WHERE clause.
*/
public EntityQuery<E> where(SqlPredicate<E> predicate) {
this.queryParameters.appendLogicalAndWhereClause(predicate);
return this;
}
/**
* Sets or appends an OR WHERE clause to the DQL statement.
*
* @param predicate The predicate describing the OR WHERE clause.
* @return This {@link EntityQuery} object, now with an (appended) OR WHERE clause.
*/
public EntityQuery<E> orWhere(SqlPredicate<E> predicate) {
this.queryParameters.appendLogicalOrWhereClause(predicate);
return this;
}
//endregion
//region Order By
/**
* Sets a single column as the ORDER BY clause for the DQL statement in an ascending manner.
*
* @param function The column to order by.
* @return This {@link EntityQuery} object, now with a ORDER BY clause.
*/
public EntityQuery<E> orderBy(SqlFunction<E, ?> function) {
return this.orderBy(function, OrderTypes.ASCENDING);
}
/**
* Sets an ORDER BY clauses for the DQL statement.
*
* @param function The column to order by.
* @return This {@link EntityQuery} object, now with a ORDER BY clause.
*/
public EntityQuery<E> orderBy(SqlFunction<E, ?> function, OrderTypes orderType) {
this.queryParameters.setOrderByClause(function, orderType);
return this;
}
/**
* Sets multiple ORDER BY clauses for the DQL statement. The resulting ORDER BY statement will coalesce the passed columns.
*
* @param functions The columns to order by in a coalescing manner.
* @return This {@link EntityQuery} object, now with a coalesced ORDER BY clause.
*/
public EntityQuery<E> orderBy(SqlFunction<E, ?>[] functions) {
if (functions == null) {
return this;
}
return this.orderBy(Arrays.asList(functions), OrderTypes.ASCENDING);
}
/**
* Sets multiple ORDER BY clauses for the DQL statement. The resulting ORDER BY statement will coalesce the passed columns.
*
* @param functions The columns to order by in a coalescing manner.
* @return This {@link EntityQuery} object, now with a coalesced ORDER BY clause.
*/
public EntityQuery<E> orderBy(SqlFunction<E, ?>[] functions, OrderTypes orderType) {
if (functions == null) {
return this;
}
return this.orderBy(Arrays.asList(functions), orderType);
}
/**
* Sets multiple ORDER BY clauses for the DQL statement. The resulting ORDER BY statement will coalesce the passed columns.
*
* @param functions The columns to order by in a coalescing manner.
* @return This {@link EntityQuery} object, now with a coalesced ORDER BY clause.
*/
public EntityQuery<E> orderBy(List<SqlFunction<E, ?>> functions) {
return this.orderBy(functions, OrderTypes.ASCENDING);
}
/**
* Sets multiple ORDER BY clauses for the DQL statement. The resulting ORDER BY statement will coalesce the passed columns.
*
* @param functions The columns to order by in a coalescing manner.
* @return This {@link EntityQuery} object, now with a coalesced ORDER BY clause.
*/
public EntityQuery<E> orderBy(List<SqlFunction<E, ?>> functions, OrderTypes orderType) {
this.queryParameters.setOrderByClause(functions, orderType);
return this;
}
//endregion
//region Group By
public EntityQuery<E> groupBy(SqlFunction<E, ?> groupBy) {
this.queryParameters.setGroupBy(groupBy);
return this;
}
public EntityQuery<E> groupBy(SqlFunction<E, ?>... groupBy) {
this.queryParameters.setGroupBy(Arrays.asList(groupBy));
return this;
}
//endregion
//region Then By
/**
* Sets a single column as the ORDER BY clause for the DQL statement in an ascending manner.
*
* @param function The column to order by.
* @return This {@link EntityQuery} object, now with a ORDER BY clause.
*/
public EntityQuery<E> thenBy(SqlFunction<E, ?> function) {
return this.thenBy(function, OrderTypes.ASCENDING);
}
/**
* Sets an ORDER BY clauses for the DQL statement.
*
* @param function The column to order by.
* @return This {@link EntityQuery} object, now with a ORDER BY clause.
*/
public EntityQuery<E> thenBy(SqlFunction<E, ?> function, OrderTypes orderType) {
this.queryParameters.addOrderByColumns(function, orderType);
return this;
}
/**
* Sets multiple ORDER BY clauses for the DQL statement. The resulting ORDER BY statement will coalesce the passed columns.
*
* @param functions The columns to order by in a coalescing manner.
* @return This {@link EntityQuery} object, now with a coalesced ORDER BY clause.
*/
public EntityQuery<E> thenBy(SqlFunction<E, ?>[] functions) {
return this.thenBy(Arrays.asList(functions), OrderTypes.ASCENDING);
}
/**
* Sets multiple ORDER BY clauses for the DQL statement. The resulting ORDER BY statement will coalesce the passed columns.
*
* @param functions The columns to order by in a coalescing manner.
* @return This {@link EntityQuery} object, now with a coalesced ORDER BY clause.
*/
public EntityQuery<E> thenBy(SqlFunction<E, ?>[] functions, OrderTypes orderType) {
return this.thenBy(Arrays.asList(functions), orderType);
}
/**
* Sets multiple ORDER BY clauses for the DQL statement. The resulting ORDER BY statement will coalesce the passed columns.
*
* @param functions The columns to order by in a coalescing manner.
* @return This {@link EntityQuery} object, now with a coalesced ORDER BY clause.
*/
public EntityQuery<E> thenBy(List<SqlFunction<E, ?>> functions) {
return this.thenBy(functions, OrderTypes.ASCENDING);
}
/**
* Sets multiple ORDER BY clauses for the DQL statement. The resulting ORDER BY statement will coalesce the passed columns.
*
* @param functions The columns to order by in a coalescing manner.
* @return This {@link EntityQuery} object, now with a coalesced ORDER BY clause.
*/
public EntityQuery<E> thenBy(List<SqlFunction<E, ?>> functions, OrderTypes orderType) {
this.queryParameters.addOrderByColumns(functions, orderType);
return this;
}
//endregion
//region Limit
/**
* Limits the result of the rows returned to a maximum of the passed integer with an offset.
* For example, the call <code>.limit(10, 5)</code> would return the rows 6-15.
*
* @param limit The maximum of rows to be returned.
* @param offset The offset of the limit.
* @return This {@link EntityQuery} object, now with a LIMIT with an OFFSET.
*/
public EntityQuery<E> limit(int limit, int offset) {
this.queryParameters.setLimit(limit);
this.queryParameters.setLimitOffset(offset);
return this;
}
/**
* Limits the result of the rows returned to a maximum of the passed integer.
*
* @param limit The maximum of rows to be returned.
* @return This {@link EntityQuery} object, now with a LIMIT.
*/
public EntityQuery<E> limit(int limit) {
this.queryParameters.setLimit(limit);
return this;
}
//endregion
/**
* Adds a DISTINCT modifier to the query.
*
* @return This {@link EntityQuery} object, now with a DISTINCT clause.
*/
public EntityQuery<E> distinct() {
this.queryParameters.setDistinct();
return this;
}
/**
* Selects only a single column from a table. This is meant if you don't want to fetch an entire entity from the database.
*
* @param projection The column to project to.
* @param <R> The type of the column you want to retrieve.
* @return A queryable containing the projection.
*/
public <R> Queryable<R> project(SqlFunction<E, R> projection) {
@SuppressWarnings("unchecked") var returnType = (Class<R>) LambdaExpression.parse(projection).getBody().getResultType();
var queryBuilder = new ProjectionQueryBuilder<>(projection, this.getTableName(), (QueryBuilder<E>) this.queryBuilder);
return new EntityProjectionQuery<>(returnType, queryBuilder, this.queryParameters, this.transactionManager);
}
/**
* Gets the first record of a result. This method should be used when only one record is expected, i.e. when filtering by a unique identifier such as an id.
*
* @return The first row as an entity wrapped in an {@link Optional} if there is at least one row.
* Otherwise {@link Optional#empty()} is returned.
*/
@Override
public Optional<E> first() {
this.limit(1);
try {
return transactionManager.transactAndReturn(connection -> {
return this.mapper.map(connection.execute(getQuery()));
});
} catch (SQLException e) {
e.printStackTrace();
return Optional.empty();
}
}
/**
* Executes the query and returns the result as a {@link List}
*
* @return A list of entities representing the result rows.
*/
@Override
public List<E> toList() {
try {
return transactionManager.transactAndReturn(connection -> {
return this.mapper.mapToList(connection.execute(getQuery()));
});
} catch (SQLException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
/**
* Executes the query and returns the result as a {@link Stream}
*
* @return A list of entities representing the result rows.
*/
@Override
public Stream<E> toStream() {
try {
return transactionManager.transactAndReturn(connection -> {
return this.mapper.mapToStream(connection.execute(getQuery()));
});
} catch (SQLException e) {
e.printStackTrace();
return Stream.empty();
}
}
/**
* Executes a new query and returns the result as an array.
*
* @return An array of entities representing the result rows.
*/
@Override
@SuppressWarnings("unchecked")
public E[] toArray() {
try {
return transactionManager.transactAndReturn(connection -> {
return this.mapper.mapToArray(connection.execute(getQuery()));
});
} catch (SQLException e) {
e.printStackTrace();
return (E[]) Array.newInstance(this.type, 0);
}
}
/**
* Executes a new query and returns the result as a {@link Map}.
*
* @param keyMapping The field representing the keys of the map.
* @param valueMapping The field representing the values of the map.
* @return A map containing the result of the query.
*/
@Override
public <K, V> Map<K, V> toMap(Function<E, K> keyMapping, Function<E, V> valueMapping) {
try {
return transactionManager.transactAndReturn(connection -> {
return this.mapper.mapToMap(connection.execute(getQuery()), keyMapping, valueMapping);
});
} catch (SQLException e) {
e.printStackTrace();
return Collections.emptyMap();
}
}
/**
* Executes the query and returns the result as a {@link Set}.
*
* @return A set of entities representing the result rows.
*/
@Override
public Set<E> toSet() {
try {
return transactionManager.transactAndReturn(connection -> {
return this.mapper.mapToSet(connection.execute(getQuery()));
});
} catch (SQLException e) {
e.printStackTrace();
return Collections.emptySet();
}
}
@Override
public String getQuery() {
return this.queryBuilder.build(this.queryParameters);
}
/**
* Gets the table name which this query targets.
*
* @return The table name which this query targets.
*/
protected String getTableName() {
return tableModule.getTableName(this.type);
}
}