/
StatelessSessionImpl.java
executable file
·745 lines (634 loc) · 20.8 KB
/
StatelessSessionImpl.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
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* 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.internal;
import java.io.Serializable;
import java.sql.Connection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.transaction.SystemException;
import org.hibernate.CacheMode;
import org.hibernate.Criteria;
import org.hibernate.EntityMode;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.MappingException;
import org.hibernate.ScrollMode;
import org.hibernate.SessionException;
import org.hibernate.StatelessSession;
import org.hibernate.UnresolvableObjectException;
import org.hibernate.cache.spi.access.EntityDataAccess;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.internal.StatefulPersistenceContext;
import org.hibernate.engine.internal.Versioning;
import org.hibernate.engine.query.spi.HQLQueryPlan;
import org.hibernate.engine.query.spi.NativeSQLQueryPlan;
import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.id.IdentifierGeneratorHelper;
import org.hibernate.loader.criteria.CriteriaLoader;
import org.hibernate.loader.custom.CustomLoader;
import org.hibernate.loader.custom.CustomQuery;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.OuterJoinLoadable;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.query.spi.ScrollableResultsImplementor;
/**
* @author Gavin King
* @author Steve Ebersole
*/
public class StatelessSessionImpl extends AbstractSharedSessionContract implements StatelessSession {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( StatelessSessionImpl.class );
private static LoadQueryInfluencers NO_INFLUENCERS = new LoadQueryInfluencers( null ) {
@Override
public String getInternalFetchProfile() {
return null;
}
@Override
public void setInternalFetchProfile(String internalFetchProfile) {
}
};
private final PersistenceContext temporaryPersistenceContext = new StatefulPersistenceContext( this );
private final boolean connectionProvided;
private final boolean allowBytecodeProxy;
StatelessSessionImpl(SessionFactoryImpl factory, SessionCreationOptions options) {
super( factory, options );
connectionProvided = options.getConnection() != null;
allowBytecodeProxy = getFactory().getSessionFactoryOptions().isEnhancementAsProxyEnabled();
}
@Override
public boolean shouldAutoJoinTransaction() {
return true;
}
// inserts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public Serializable insert(Object entity) {
checkOpen();
return insert( null, entity );
}
@Override
public Serializable insert(String entityName, Object entity) {
checkOpen();
EntityPersister persister = getEntityPersister( entityName, entity );
Serializable id = persister.getIdentifierGenerator().generate( this, entity );
Object[] state = persister.getPropertyValues( entity );
if ( persister.isVersioned() ) {
boolean substitute = Versioning.seedVersion(
state,
persister.getVersionProperty(),
persister.getVersionType(),
this
);
if ( substitute ) {
persister.setPropertyValues( entity, state );
}
}
if ( id == IdentifierGeneratorHelper.POST_INSERT_INDICATOR ) {
id = persister.insert( state, entity, this );
}
else {
persister.insert( id, state, entity, this );
}
persister.setIdentifier( entity, id, this );
return id;
}
// deletes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public void delete(Object entity) {
checkOpen();
delete( null, entity );
}
@Override
public void delete(String entityName, Object entity) {
checkOpen();
EntityPersister persister = getEntityPersister( entityName, entity );
Serializable id = persister.getIdentifier( entity, this );
Object version = persister.getVersion( entity );
persister.delete( id, version, entity, this );
}
// updates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public void update(Object entity) {
checkOpen();
update( null, entity );
}
@Override
public void update(String entityName, Object entity) {
checkOpen();
EntityPersister persister = getEntityPersister( entityName, entity );
Serializable id = persister.getIdentifier( entity, this );
Object[] state = persister.getPropertyValues( entity );
Object oldVersion;
if ( persister.isVersioned() ) {
oldVersion = persister.getVersion( entity );
Object newVersion = Versioning.increment( oldVersion, persister.getVersionType(), this );
Versioning.setVersion( state, newVersion, persister );
persister.setPropertyValues( entity, state );
}
else {
oldVersion = null;
}
persister.update( id, state, null, false, null, oldVersion, entity, null, this );
}
// loading ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public Object get(Class entityClass, Serializable id) {
return get( entityClass.getName(), id );
}
@Override
public Object get(Class entityClass, Serializable id, LockMode lockMode) {
return get( entityClass.getName(), id, lockMode );
}
@Override
public Object get(String entityName, Serializable id) {
return get( entityName, id, LockMode.NONE );
}
@Override
public Object get(String entityName, Serializable id, LockMode lockMode) {
checkOpen();
Object result = getFactory().getMetamodel().entityPersister( entityName )
.load( id, null, getNullSafeLockMode( lockMode ), this );
if ( temporaryPersistenceContext.isLoadFinished() ) {
temporaryPersistenceContext.clear();
}
return result;
}
@Override
public void refresh(Object entity) {
refresh( bestGuessEntityName( entity ), entity, LockMode.NONE );
}
@Override
public void refresh(String entityName, Object entity) {
refresh( entityName, entity, LockMode.NONE );
}
@Override
public void refresh(Object entity, LockMode lockMode) {
refresh( bestGuessEntityName( entity ), entity, lockMode );
}
@Override
public void refresh(String entityName, Object entity, LockMode lockMode) {
final EntityPersister persister = this.getEntityPersister( entityName, entity );
final Serializable id = persister.getIdentifier( entity, this );
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Refreshing transient {0}", MessageHelper.infoString( persister, id, this.getFactory() ) );
}
// TODO : can this ever happen???
// EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
// if ( source.getPersistenceContext().getEntry( key ) != null ) {
// throw new PersistentObjectException(
// "attempted to refresh transient instance when persistent " +
// "instance was already associated with the Session: " +
// MessageHelper.infoString( persister, id, source.getFactory() )
// );
// }
if ( persister.canWriteToCache() ) {
final EntityDataAccess cacheAccess = persister.getCacheAccessStrategy();
if ( cacheAccess != null ) {
final Object ck = cacheAccess.generateCacheKey(
id,
persister,
getFactory(),
getTenantIdentifier()
);
cacheAccess.evict( ck );
}
}
String previousFetchProfile = this.getLoadQueryInfluencers().getInternalFetchProfile();
Object result = null;
try {
this.getLoadQueryInfluencers().setInternalFetchProfile( "refresh" );
result = persister.load( id, entity, getNullSafeLockMode( lockMode ), this );
}
finally {
this.getLoadQueryInfluencers().setInternalFetchProfile( previousFetchProfile );
}
UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() );
}
@Override
public Object immediateLoad(String entityName, Serializable id) throws HibernateException {
if ( getPersistenceContext().isLoadFinished() ) {
throw new SessionException( "proxies cannot be fetched by a stateless session" );
}
// unless we are still in the process of handling a top-level load
return get( entityName, id );
}
@Override
public void initializeCollection(
PersistentCollection collection,
boolean writing) throws HibernateException {
throw new SessionException( "collections cannot be fetched by a stateless session" );
}
@Override
public Object instantiate(
String entityName,
Serializable id) throws HibernateException {
checkOpen();
return getFactory().getMetamodel().entityPersister( entityName ).instantiate( id, this );
}
@Override
public Object internalLoad(
String entityName,
Serializable id,
boolean eager,
boolean nullable) throws HibernateException {
checkOpen();
EntityPersister persister = getFactory().getMetamodel().entityPersister( entityName );
final EntityKey entityKey = generateEntityKey( id, persister );
// first, try to load it from the temp PC associated to this SS
Object loaded = temporaryPersistenceContext.getEntity( entityKey );
if ( loaded != null ) {
// we found it in the temp PC. Should indicate we are in the midst of processing a result set
// containing eager fetches via join fetch
return loaded;
}
if ( !eager ) {
// caller did not request forceful eager loading, see if we can create
// some form of proxy
// first, check to see if we can use "bytecode proxies"
if ( allowBytecodeProxy
&& persister.getEntityMetamodel().getBytecodeEnhancementMetadata().isEnhancedForLazyLoading() ) {
// we cannot use bytecode proxy for entities with subclasses
if ( !persister.getEntityMetamodel().hasSubclasses() ) {
final Object entity = persister.getEntityTuplizer().instantiate( id, this );
persister.getEntityMetamodel()
.getBytecodeEnhancementMetadata()
.injectEnhancedEntityAsProxyInterceptor( entity, entityKey, this );
getPersistenceContext().addEntity( entityKey, entity );
return entity;
}
}
// we could not use bytecode proxy, check to see if we can use HibernateProxy
if ( persister.hasProxy() ) {
final Object existingProxy = getPersistenceContext().getProxy( entityKey );
if ( existingProxy != null ) {
return getPersistenceContext().narrowProxy( existingProxy, persister, entityKey, null );
}
else {
final Object proxy = persister.createProxy( id, this );
getPersistenceContext().addProxy( entityKey, proxy );
return proxy;
}
}
}
// otherwise immediately materialize it
return get( entityName, id );
}
@Override
public Iterator iterate(String query, QueryParameters queryParameters) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Iterator iterateFilter(Object collection, String filter, QueryParameters queryParameters)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public List listFilter(Object collection, String filter, QueryParameters queryParameters)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean isAutoCloseSessionEnabled() {
return getFactory().getSessionFactoryOptions().isAutoCloseSessionEnabled();
}
@Override
public boolean shouldAutoClose() {
return isAutoCloseSessionEnabled() && !isClosed();
}
private boolean isFlushModeNever() {
return false;
}
private void managedClose() {
if ( isClosed() ) {
throw new SessionException( "Session was already closed!" );
}
close();
}
private void managedFlush() {
checkOpen();
getJdbcCoordinator().executeBatch();
}
@Override
public String bestGuessEntityName(Object object) {
if ( object instanceof HibernateProxy ) {
object = ( (HibernateProxy) object ).getHibernateLazyInitializer().getImplementation();
}
return guessEntityName( object );
}
@Override
public Connection connection() {
checkOpen();
return getJdbcCoordinator().getLogicalConnection().getPhysicalConnection();
}
@Override
public int executeUpdate(String query, QueryParameters queryParameters) throws HibernateException {
checkOpen();
queryParameters.validateParameters();
HQLQueryPlan plan = getQueryPlan( query, false );
boolean success = false;
int result = 0;
try {
result = plan.performExecuteUpdate( queryParameters, this );
success = true;
}
finally {
afterOperation( success );
}
temporaryPersistenceContext.clear();
return result;
}
@Override
public CacheMode getCacheMode() {
return CacheMode.IGNORE;
}
@Override
public void setCacheMode(CacheMode cm) {
throw new UnsupportedOperationException();
}
@Override
public void setFlushMode(FlushMode fm) {
throw new UnsupportedOperationException();
}
@Override
public void setHibernateFlushMode(FlushMode flushMode) {
throw new UnsupportedOperationException();
}
@Override
public int getDontFlushFromFind() {
return 0;
}
@Override
public Serializable getContextEntityIdentifier(Object object) {
checkOpen();
return null;
}
public EntityMode getEntityMode() {
return EntityMode.POJO;
}
@Override
public String guessEntityName(Object entity) throws HibernateException {
checkOpen();
return entity.getClass().getName();
}
@Override
public EntityPersister getEntityPersister(String entityName, Object object)
throws HibernateException {
checkOpen();
if ( entityName == null ) {
return getFactory().getMetamodel().entityPersister( guessEntityName( object ) );
}
else {
return getFactory().getMetamodel().entityPersister( entityName ).getSubclassEntityPersister( object, getFactory() );
}
}
@Override
public Object getEntityUsingInterceptor(EntityKey key) throws HibernateException {
checkOpen();
final Object result = getPersistenceContext().getEntity( key );
if ( result != null ) {
return result;
}
final Object newObject = getInterceptor().getEntity( key.getEntityName(), key.getIdentifier() );
if ( newObject != null ) {
getPersistenceContext().addEntity( key, newObject );
return newObject;
}
return null;
}
@Override
public PersistenceContext getPersistenceContext() {
return temporaryPersistenceContext;
}
@Override
public void setAutoClear(boolean enabled) {
throw new UnsupportedOperationException();
}
@Override
protected Object load(String entityName, Serializable identifier) {
return null;
}
@Override
public boolean isEventSource() {
return false;
}
public boolean isDefaultReadOnly() {
return false;
}
public void setDefaultReadOnly(boolean readOnly) throws HibernateException {
if ( readOnly ) {
throw new UnsupportedOperationException();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//TODO: COPY/PASTE FROM SessionImpl, pull up!
@Override
public List list(String query, QueryParameters queryParameters) throws HibernateException {
checkOpen();
queryParameters.validateParameters();
HQLQueryPlan plan = getQueryPlan( query, false );
boolean success = false;
List results = Collections.EMPTY_LIST;
try {
results = plan.performList( queryParameters, this );
success = true;
}
finally {
afterOperation( success );
}
temporaryPersistenceContext.clear();
return results;
}
public void afterOperation(boolean success) {
if ( !isTransactionInProgress() ) {
getJdbcCoordinator().afterTransaction();
}
}
@Override
public Criteria createCriteria(Class persistentClass, String alias) {
checkOpen();
return new CriteriaImpl( persistentClass.getName(), alias, this );
}
@Override
public Criteria createCriteria(String entityName, String alias) {
checkOpen();
return new CriteriaImpl( entityName, alias, this );
}
@Override
public Criteria createCriteria(Class persistentClass) {
checkOpen();
return new CriteriaImpl( persistentClass.getName(), this );
}
@Override
public Criteria createCriteria(String entityName) {
checkOpen();
return new CriteriaImpl( entityName, this );
}
@Override
public ScrollableResultsImplementor scroll(Criteria criteria, ScrollMode scrollMode) {
// TODO: Is this guaranteed to always be CriteriaImpl?
CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
checkOpen();
String entityName = criteriaImpl.getEntityOrClassName();
CriteriaLoader loader = new CriteriaLoader(
getOuterJoinLoadable( entityName ),
getFactory(),
criteriaImpl,
entityName,
getLoadQueryInfluencers()
);
return loader.scroll( this, scrollMode );
}
@Override
@SuppressWarnings({"unchecked"})
public List list(Criteria criteria) throws HibernateException {
// TODO: Is this guaranteed to always be CriteriaImpl?
CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
checkOpen();
String[] implementors = getFactory().getMetamodel().getImplementors( criteriaImpl.getEntityOrClassName() );
int size = implementors.length;
CriteriaLoader[] loaders = new CriteriaLoader[size];
for ( int i = 0; i < size; i++ ) {
loaders[i] = new CriteriaLoader(
getOuterJoinLoadable( implementors[i] ),
getFactory(),
criteriaImpl,
implementors[i],
getLoadQueryInfluencers()
);
}
List results = Collections.EMPTY_LIST;
boolean success = false;
try {
for ( int i = 0; i < size; i++ ) {
final List currentResults = loaders[i].list( this );
currentResults.addAll( results );
results = currentResults;
}
success = true;
}
finally {
afterOperation( success );
}
temporaryPersistenceContext.clear();
return results;
}
private OuterJoinLoadable getOuterJoinLoadable(String entityName) throws MappingException {
EntityPersister persister = getFactory().getMetamodel().entityPersister( entityName );
if ( !( persister instanceof OuterJoinLoadable ) ) {
throw new MappingException( "class persister is not OuterJoinLoadable: " + entityName );
}
return (OuterJoinLoadable) persister;
}
@Override
public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters)
throws HibernateException {
checkOpen();
CustomLoader loader = new CustomLoader( customQuery, getFactory() );
boolean success = false;
List results;
try {
results = loader.list( this, queryParameters );
success = true;
}
finally {
afterOperation( success );
}
temporaryPersistenceContext.clear();
return results;
}
@Override
public ScrollableResultsImplementor scrollCustomQuery(CustomQuery customQuery, QueryParameters queryParameters)
throws HibernateException {
checkOpen();
CustomLoader loader = new CustomLoader( customQuery, getFactory() );
return loader.scroll( queryParameters, this );
}
@Override
public ScrollableResultsImplementor scroll(String query, QueryParameters queryParameters) throws HibernateException {
checkOpen();
HQLQueryPlan plan = getQueryPlan( query, false );
return plan.performScroll( queryParameters, this );
}
@Override
public void afterScrollOperation() {
temporaryPersistenceContext.clear();
}
@Override
public void flush() {
}
@Override
public LoadQueryInfluencers getLoadQueryInfluencers() {
return NO_INFLUENCERS;
}
@Override
public int executeNativeUpdate(
NativeSQLQuerySpecification nativeSQLQuerySpecification,
QueryParameters queryParameters) throws HibernateException {
checkOpen();
queryParameters.validateParameters();
NativeSQLQueryPlan plan = getNativeQueryPlan( nativeSQLQuerySpecification );
boolean success = false;
int result = 0;
try {
result = plan.performExecuteUpdate( queryParameters, this );
success = true;
}
finally {
afterOperation( success );
}
temporaryPersistenceContext.clear();
return result;
}
@Override
public void afterTransactionBegin() {
}
@Override
public void beforeTransactionCompletion() {
flushBeforeTransactionCompletion();
}
@Override
public void afterTransactionCompletion(boolean successful, boolean delayed) {
if ( shouldAutoClose() && !isClosed() ) {
managedClose();
}
}
@Override
public boolean isTransactionInProgress() {
return connectionProvided || super.isTransactionInProgress();
}
@Override
public void flushBeforeTransactionCompletion() {
boolean flush = false;
try {
flush = (
!isClosed()
&& !isFlushModeNever()
&& !JtaStatusHelper.isRollback(
getJtaPlatform().getCurrentStatus()
) );
}
catch (SystemException se) {
throw new HibernateException( "could not determine transaction status in beforeCompletion()", se );
}
if ( flush ) {
managedFlush();
}
}
private JtaPlatform getJtaPlatform() {
return getFactory().getServiceRegistry().getService( JtaPlatform.class );
}
private LockMode getNullSafeLockMode(LockMode lockMode) {
return lockMode == null ? LockMode.NONE : lockMode;
}
}