/
HibernateOrmSearchQueryAdapter.java
328 lines (277 loc) · 10.4 KB
/
HibernateOrmSearchQueryAdapter.java
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
/*
* Hibernate Search, full-text search for your domain model
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.search.mapper.orm.search.query.impl;
import java.lang.invoke.MethodHandles;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.ScrollMode;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.graph.GraphSemantic;
import org.hibernate.graph.RootGraph;
import org.hibernate.graph.spi.RootGraphImplementor;
import org.hibernate.query.ResultListTransformer;
import org.hibernate.query.TupleTransformer;
import org.hibernate.query.internal.QueryOptionsImpl;
import org.hibernate.query.spi.AbstractQuery;
import org.hibernate.query.spi.ParameterMetadataImplementor;
import org.hibernate.query.spi.QueryImplementor;
import org.hibernate.query.spi.QueryParameterBindings;
import org.hibernate.query.spi.ScrollableResultsImplementor;
import org.hibernate.search.engine.search.query.SearchQuery;
import org.hibernate.search.engine.search.query.spi.SearchQueryImplementor;
import org.hibernate.search.mapper.orm.loading.impl.EntityGraphHint;
import org.hibernate.search.mapper.orm.loading.impl.MutableEntityLoadingOptions;
import org.hibernate.search.mapper.orm.logging.impl.Log;
import org.hibernate.search.mapper.orm.search.query.spi.HibernateOrmSearchQueryHints;
import org.hibernate.search.mapper.orm.search.query.spi.HibernateOrmSearchScrollableResultsAdapter;
import org.hibernate.search.util.common.SearchTimeoutException;
import org.hibernate.search.util.common.annotation.impl.SuppressForbiddenApis;
import org.hibernate.search.util.common.logging.impl.LoggerFactory;
import jakarta.persistence.LockModeType;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.QueryTimeoutException;
@SuppressForbiddenApis(reason = "We need to extend the internal AbstractProducedQuery"
+ " in order to implement a org.hibernate.query.Query")
@SuppressWarnings("unchecked") // For some reason javac issues warnings for all methods returning this; IDEA doesn't.
public final class HibernateOrmSearchQueryAdapter<R> extends AbstractQuery<R> {
public static <R> HibernateOrmSearchQueryAdapter<R> create(SearchQuery<R> query) {
return query.extension( HibernateOrmSearchQueryAdapterExtension.get() );
}
private static final Log log = LoggerFactory.make( Log.class, MethodHandles.lookup() );
private final SearchQueryImplementor<R> delegate;
private final SessionImplementor sessionImplementor;
private final MutableEntityLoadingOptions loadingOptions;
private final QueryOptionsImpl queryOptions = new QueryOptionsImpl();
HibernateOrmSearchQueryAdapter(SearchQueryImplementor<R> delegate, SessionImplementor sessionImplementor,
MutableEntityLoadingOptions loadingOptions) {
super( sessionImplementor );
this.delegate = delegate;
this.sessionImplementor = sessionImplementor;
this.loadingOptions = loadingOptions;
}
@Override
public String toString() {
return "HibernateOrmSearchQueryAdapter(" + getQueryString() + ")";
}
//-------------------------------------------------------------
// Supported ORM/JPA query methods
//-------------------------------------------------------------
@Override
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> cls) {
if ( cls.equals( SearchQuery.class ) ) {
return (T) delegate;
}
else if ( cls.isInstance( this ) ) {
return (T) this;
}
else {
throw new PersistenceException( "Unrecognized unwrap type [" + cls.getName() + "]" );
}
}
@Override
public List<R> list() {
try {
return super.list();
}
catch (SearchTimeoutException e) {
throw new QueryTimeoutException( e );
}
}
@Override
public String getQueryString() {
return delegate.queryString();
}
@Override
public QueryOptionsImpl getQueryOptions() {
return queryOptions;
}
@Override
public HibernateOrmSearchQueryAdapter<R> setHint(String hintName, Object value) {
switch ( hintName ) {
case HibernateOrmSearchQueryHints.JAVAX_TIMEOUT:
case HibernateOrmSearchQueryHints.JAKARTA_TIMEOUT:
delegate.failAfter( hintValueToLong( value ), TimeUnit.MILLISECONDS );
break;
case HibernateOrmSearchQueryHints.HIBERNATE_TIMEOUT:
setTimeout( hintValueToInteger( value ) );
break;
case HibernateOrmSearchQueryHints.JAVAX_FETCHGRAPH:
case HibernateOrmSearchQueryHints.JAKARTA_FETCHGRAPH:
case HibernateOrmSearchQueryHints.JAVAX_LOADGRAPH:
case HibernateOrmSearchQueryHints.JAKARTA_LOADGRAPH:
applyEntityGraphQueryHint( hintName, hintValueToEntityGraph( value ) );
break;
default:
log.ignoringUnrecognizedQueryHint( hintName );
break;
}
return this;
}
@Override
public HibernateOrmSearchQueryAdapter<R> setTimeout(int timeout) {
delegate.failAfter( timeout, TimeUnit.SECONDS );
return this;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public HibernateOrmSearchQueryAdapter<R> applyGraph(RootGraph graph, GraphSemantic semantic) {
loadingOptions.entityGraphHint( new EntityGraphHint<>( graph, semantic ), true );
return this;
}
@Override
protected void applyEntityGraphQueryHint(String hintName, RootGraphImplementor<?> entityGraph) {
GraphSemantic graphSemantic = GraphSemantic.fromJpaHintName( hintName );
this.applyGraph( entityGraph, graphSemantic );
}
@Override
public ScrollableResultsImplementor<R> scroll() {
return scroll( ScrollMode.FORWARD_ONLY );
}
@Override
public ScrollableResultsImplementor<R> scroll(ScrollMode scrollMode) {
if ( !ScrollMode.FORWARD_ONLY.equals( scrollMode ) ) {
throw log.canOnlyUseScrollWithScrollModeForwardsOnly( scrollMode );
}
extractQueryOptions();
int chunkSize = loadingOptions.fetchSize();
return new HibernateOrmSearchScrollableResultsAdapter<>( delegate.scroll( chunkSize ), getMaxResults(),
Function.identity() );
}
@Override
public SharedSessionContractImplementor getSession() {
return sessionImplementor;
}
@Override
protected List<R> doList() {
// Do not use getMaxRows()/getFirstRow() directly, they return weird values to comply with the JPA spec
Integer limit = getQueryOptions().getLimit().getMaxRows();
Integer offset = getQueryOptions().getLimit().getFirstRow();
return delegate.fetchHits( offset, limit );
}
@Override
protected void beforeQuery(boolean requiresTxn) {
super.beforeQuery( requiresTxn );
extractQueryOptions();
}
private void extractQueryOptions() {
Integer queryFetchSize = getQueryOptions().getFetchSize();
if ( queryFetchSize != null ) {
loadingOptions.fetchSize( queryFetchSize );
}
Integer queryTimeout = getQueryOptions().getTimeout();
if ( queryTimeout != null ) {
delegate.failAfter( queryTimeout, TimeUnit.SECONDS );
}
}
//-------------------------------------------------------------
// Unsupported ORM/JPA query methods
//-------------------------------------------------------------
@Override
public Map<String, Object> getHints() {
throw new UnsupportedOperationException( "Not implemented yet" );
}
@Override
public ParameterMetadataImplementor getParameterMetadata() {
throw parametersNoSupported();
}
@Override
public QueryParameterBindings getParameterBindings() {
// parameters not supported in Hibernate Search queries
return QueryParameterBindings.NO_PARAM_BINDINGS;
}
@Override
protected QueryParameterBindings getQueryParameterBindings() {
// parameters not supported in Hibernate Search queries
return QueryParameterBindings.NO_PARAM_BINDINGS;
}
@Override
public HibernateOrmSearchQueryAdapter<R> setParameterList(String name, Object[] values) {
throw parametersNoSupported();
}
@Override
public QueryImplementor<R> setParameterList(String s, Collection collection, Class aClass) {
throw parametersNoSupported();
}
@Override
public QueryImplementor<R> setParameterList(int i, Collection collection, Class aClass) {
throw parametersNoSupported();
}
private UnsupportedOperationException parametersNoSupported() {
return new UnsupportedOperationException( "Parameters are not supported in Hibernate Search queries" );
}
@Override
public QueryImplementor<R> setTupleTransformer(TupleTransformer transformer) {
throw resultOrTupleTransformerNotImplemented();
}
@Override
public QueryImplementor<R> setResultListTransformer(ResultListTransformer resultListTransformer) {
throw resultOrTupleTransformerNotImplemented();
}
private UnsupportedOperationException resultOrTupleTransformerNotImplemented() {
return new UnsupportedOperationException( "Result transformers are not supported in Hibernate Search queries" );
}
@Override
public HibernateOrmSearchQueryAdapter<R> setLockMode(LockModeType lockModeType) {
throw lockOptionsNotSupported();
}
@Override
public LockModeType getLockMode() {
throw lockOptionsNotSupported();
}
@Override
public LockOptions getLockOptions() {
/*
* Ideally we'd throw an UnsupportedOperationException,
* but we can't because getLockOptions is called
* when AbstractProducedQuery converts exceptions.
* So let's just return null, which at least seems acceptable for AbstractProducedQuery.
*/
return null;
}
private UnsupportedOperationException lockOptionsNotSupported() {
return new UnsupportedOperationException( "Lock options are not supported in Hibernate Search queries" );
}
@Override
public int executeUpdate() throws HibernateException {
return doExecuteUpdate();
}
@Override
protected int doExecuteUpdate() {
throw new UnsupportedOperationException( "executeUpdate is not supported in Hibernate Search queries" );
}
@Override
public HibernateOrmSearchQueryAdapter<R> setLockMode(String alias, LockMode lockMode) {
throw lockOptionsNotSupported();
}
private static long hintValueToLong(Object value) {
if ( value instanceof Number ) {
return ( (Number) value ).longValue();
}
else {
return Long.parseLong( String.valueOf( value ) );
}
}
private static int hintValueToInteger(Object value) {
if ( value instanceof Number ) {
return ( (Number) value ).intValue();
}
else {
return Integer.parseInt( String.valueOf( value ) );
}
}
private static RootGraphImplementor<?> hintValueToEntityGraph(Object value) {
return (RootGraphImplementor<?>) value;
}
}