forked from OpenFeign/querydsl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractHibernateQuery.java
More file actions
422 lines (379 loc) · 11.4 KB
/
AbstractHibernateQuery.java
File metadata and controls
422 lines (379 loc) · 11.4 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
412
413
414
415
416
417
418
419
420
421
422
/*
* Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.querydsl.jpa.hibernate;
import com.querydsl.core.CloseableIterator;
import com.querydsl.core.DefaultQueryMetadata;
import com.querydsl.core.NonUniqueResultException;
import com.querydsl.core.QueryException;
import com.querydsl.core.QueryFlag;
import com.querydsl.core.QueryMetadata;
import com.querydsl.core.QueryModifiers;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ConstantImpl;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.FactoryExpression;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.SubQueryExpression;
import com.querydsl.jpa.FactoryExpressionTransformer;
import com.querydsl.jpa.HQLTemplates;
import com.querydsl.jpa.JPAQueryBase;
import com.querydsl.jpa.JPQLTemplates;
import com.querydsl.jpa.ScrollableResultsIterator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import org.hibernate.FlushMode;
import org.hibernate.LockMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.StatelessSession;
import org.hibernate.query.Query;
import org.jetbrains.annotations.Nullable;
/**
* Abstract base class for Hibernate API based implementations of the JPQL interface
*
* @param <T> result type
* @param <Q> concrete subtype
* @author tiwe
*/
public abstract class AbstractHibernateQuery<T, Q extends AbstractHibernateQuery<T, Q>>
extends JPAQueryBase<T, Q> {
private static final Logger logger = Logger.getLogger(HibernateQuery.class.getName());
@Nullable protected Boolean cacheable, readOnly;
@Nullable protected String cacheRegion, comment;
protected int fetchSize = 0;
protected final Map<Path<?>, LockMode> lockModes = new HashMap<>();
@Nullable protected FlushMode flushMode;
private final SessionHolder session;
protected int timeout = 0;
public AbstractHibernateQuery(Session session) {
this(new DefaultSessionHolder(session), HQLTemplates.DEFAULT, new DefaultQueryMetadata());
}
public AbstractHibernateQuery(
SessionHolder session, JPQLTemplates patterns, QueryMetadata metadata) {
super(metadata, patterns);
this.session = session;
}
@Override
public long fetchCount() {
var modifiers = getMetadata().getModifiers();
try {
var query = createQuery(modifiers, true);
var rv = (Long) query.uniqueResult();
if (rv != null) {
return rv;
} else {
throw new QueryException("Query returned null");
}
} finally {
reset();
}
}
public Q with(Path<?> alias, SubQueryExpression<?> query) {
return with(alias, null, query);
}
public Q withMaterializedHint(Path<?> alias, SubQueryExpression<?> query) {
return with(alias, true, query);
}
public Q withNotMaterializedHint(Path<?> alias, SubQueryExpression<?> query) {
return with(alias, false, query);
}
public Q with(Path<?> alias, Boolean materialized, SubQueryExpression<?> query) {
Expression<?> expr =
ExpressionUtils.operation(
alias.getType(),
HQLOps.WITH,
alias,
materialized != null ? ConstantImpl.create(materialized) : null,
query);
return queryMixin.addFlag(new QueryFlag(QueryFlag.Position.WITH, expr));
}
/**
* Expose the original Hibernate query for the given projection
*
* @return query
*/
public Query createQuery() {
return createQuery(getMetadata().getModifiers(), false);
}
private Query createQuery(@Nullable QueryModifiers modifiers, boolean forCount) {
var serializer = serialize(forCount);
var queryString = serializer.toString();
logQuery(queryString);
Query query = session.createQuery(queryString);
HibernateUtil.setConstants(query, serializer.getConstants(), getMetadata().getParams());
if (fetchSize > 0) {
query.setFetchSize(fetchSize);
}
if (timeout > 0) {
query.setTimeout(timeout);
}
if (cacheable != null) {
query.setCacheable(cacheable);
}
if (cacheRegion != null) {
query.setCacheRegion(cacheRegion);
}
if (comment != null) {
query.setComment(comment);
}
if (readOnly != null) {
query.setReadOnly(readOnly);
}
for (Map.Entry<Path<?>, LockMode> entry : lockModes.entrySet()) {
query.setLockMode(entry.getKey().toString(), entry.getValue());
}
if (flushMode != null) {
query.setHibernateFlushMode(flushMode);
}
if (modifiers != null && modifiers.isRestricting()) {
Integer limit = modifiers.getLimitAsInteger();
Integer offset = modifiers.getOffsetAsInteger();
if (limit != null) {
query.setMaxResults(limit);
}
if (offset != null) {
query.setFirstResult(offset);
}
}
// set transformer, if necessary
Expression<?> projection = getMetadata().getProjection();
if (!forCount && projection instanceof FactoryExpression) {
query.setResultTransformer(
new FactoryExpressionTransformer((FactoryExpression<?>) projection));
}
return query;
}
/**
* Return the query results as an {@code Iterator}. If the query contains multiple results pre
* row, the results are returned in an instance of {@code Object[]}.<br>
* <br>
* Entities returned as results are initialized on demand. The first SQL query returns identifiers
* only.<br>
*/
@Override
public CloseableIterator<T> iterate() {
try {
var query = createQuery();
var results = query.getResultList();
return new ScrollableResultsIterator<T>(results);
} finally {
reset();
}
}
@Override
public Stream<T> stream() {
try {
var query = createQuery();
return query.getResultStream();
} finally {
reset();
}
}
@Override
@SuppressWarnings("unchecked")
public List<T> fetch() {
try {
return createQuery().list();
} finally {
reset();
}
}
@Override
public QueryResults<T> fetchResults() {
try {
var countQuery = createQuery(null, true);
long total = (Long) countQuery.uniqueResult();
if (total > 0) {
var modifiers = getMetadata().getModifiers();
var query = createQuery(modifiers, false);
@SuppressWarnings("unchecked")
List<T> list = query.list();
return new QueryResults<>(list, modifiers, total);
} else {
return QueryResults.emptyResults();
}
} finally {
reset();
}
}
protected void logQuery(String queryString) {
if (logger.isLoggable(Level.FINE)) {
var normalizedQuery = queryString.replace('\n', ' ');
logger.fine(normalizedQuery);
}
}
@Override
protected void reset() {}
/**
* Return the query results as {@code ScrollableResults}. The scrollability of the returned
* results depends upon JDBC driver support for scrollable {@code ResultSet}s.<br>
*
* @param mode scroll mode
* @return scrollable results
*/
public ScrollableResults scroll(ScrollMode mode) {
try {
return createQuery().scroll(mode);
} finally {
reset();
}
}
/**
* Enable caching of this query result set.
*
* @param cacheable Should the query results be cacheable?
*/
@SuppressWarnings("unchecked")
public Q setCacheable(boolean cacheable) {
this.cacheable = cacheable;
return (Q) this;
}
/**
* Set the name of the cache region.
*
* @param cacheRegion the name of a query cache region, or {@code null} for the default query
* cache
*/
@SuppressWarnings("unchecked")
public Q setCacheRegion(String cacheRegion) {
this.cacheRegion = cacheRegion;
return (Q) this;
}
/**
* Add a comment to the generated SQL.
*
* @param comment comment
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setComment(String comment) {
this.comment = comment;
return (Q) this;
}
/**
* Set a fetchJoin size for the underlying JDBC query.
*
* @param fetchSize the fetchJoin size
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
return (Q) this;
}
/**
* Set the lock mode for the given path.
*
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setLockMode(Path<?> path, LockMode lockMode) {
lockModes.put(path, lockMode);
return (Q) this;
}
/**
* Override the current session flush mode, just for this query.
*
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setFlushMode(FlushMode flushMode) {
this.flushMode = flushMode;
return (Q) this;
}
/**
* Entities retrieved by this query will be loaded in a read-only mode where Hibernate will never
* dirty-check them or make changes persistent.
*
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
return (Q) this;
}
/**
* Set a timeout for the underlying JDBC query.
*
* @param timeout the timeout in seconds
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setTimeout(int timeout) {
this.timeout = timeout;
return (Q) this;
}
@SuppressWarnings("unchecked")
@Override
public T fetchOne() throws NonUniqueResultException {
try {
var modifiers = getMetadata().getModifiers();
var query = createQuery(modifiers, false);
try {
return (T) query.uniqueResult();
} catch (org.hibernate.NonUniqueResultException e) {
throw new NonUniqueResultException(e);
}
} finally {
reset();
}
}
@Override
protected HQLSerializer createSerializer() {
return new HQLSerializer(getTemplates());
}
protected void clone(Q query) {
cacheable = query.cacheable;
cacheRegion = query.cacheRegion;
fetchSize = query.fetchSize;
flushMode = query.flushMode;
lockModes.putAll(query.lockModes);
readOnly = query.readOnly;
timeout = query.timeout;
}
protected abstract Q clone(SessionHolder sessionHolder);
/**
* Clone the state of this query to a new instance with the given Session
*
* @param session session
* @return cloned query
*/
public Q clone(Session session) {
return this.clone(new DefaultSessionHolder(session));
}
/**
* Clone the state of this query to a new instance with the given StatelessSession
*
* @param session session
* @return cloned query
*/
public Q clone(StatelessSession session) {
return this.clone(new StatelessSessionHolder(session));
}
/**
* Clone the state of this query to a new instance
*
* @return closed query
*/
@Override
public Q clone() {
return this.clone(this.session);
}
}