Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 114adf2dfc0c10a712a256c48211dde8d4f6e7f8 (plain) (blame)
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
/**
 * <copyright>
 *
 * Copyright (c) 2005, 2006, 2007, 2008 Springsite BV (The Netherlands) and others
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Martin Taal
 * </copyright>
 *
 * $Id: HbEntityDataStore.java,v 1.37 2011/07/05 05:09:41 mtaal Exp $
 */

package org.eclipse.emf.teneo.hibernate;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.persistence.Cache;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
import javax.persistence.Parameter;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
import javax.persistence.SynchronizationType;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.metamodel.Metamodel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.emf.teneo.PackageRegistryProvider;
import org.eclipse.emf.teneo.annotations.mapper.PersistenceFileProvider;
import org.eclipse.emf.teneo.annotations.pamodel.PAnnotatedEClass;
import org.eclipse.emf.teneo.annotations.pamodel.PAnnotatedEPackage;
import org.eclipse.emf.teneo.hibernate.auditing.AuditProcessHandler;
import org.eclipse.emf.teneo.hibernate.mapper.MappingUtil;
import org.eclipse.emf.teneo.hibernate.mapping.EMFInitializeCollectionEventListener;
import org.eclipse.emf.teneo.hibernate.mapping.eav.EAVGenericIDUserType;
import org.hibernate.Interceptor;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.ejb.Ejb3Configuration;
import org.hibernate.ejb.EntityManagerFactoryImpl;
import org.hibernate.ejb.QueryImpl;
import org.hibernate.engine.query.spi.NamedParameterDescriptor;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.AbstractQueryImpl;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;

/**
 * Adds Hibernate Entitymanager behavior to the hbDataStore.
 * 
 * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
 * @version $Revision: 1.37 $
 */
@SuppressWarnings("deprecation")
public class HbEntityDataStore extends HbDataStore implements EntityManagerFactory {

	/** The logger */
	private static Log log = LogFactory.getLog(HbEntityDataStore.class);

	/** The persistency manager factory */
	private EntityManagerFactory entityManagerFactory;

	/** The used Hibernate configuration */
	private Ejb3Configuration ejb3Configuration;

	private Field queryParametersField;

	private AuditProcessHandler auditProcessHandler;

	/** Initializes this Data Store */
	@Override
	public void initialize() {

		// start with a fresh one
		setAuditHandler(null);

		if (ejb3Configuration != null && isResetConfigurationOnInitialization()) {
			ejb3Configuration = null;
		}

		MappingUtil.registerHbExtensions(getExtensionManager());

		try {
			PackageRegistryProvider.getInstance().setThreadPackageRegistry(getPackageRegistry());

			if (log.isDebugEnabled()) {
				log.debug("Initializing EJB3 Hb Entity DataStore");
			}
			// check a few things
			if (getEPackages() == null) {
				throw new HbMapperException("EPackages are not set");
				// if (getName() == null)
				// throw new HbStoreException("Name is not set");
			}

			// reset interceptor
			setInterceptor(null);

			mapModel();

			setPropertiesInConfiguration();

			initializeDataStore();

			// wait for the session factory until the database is (re)created
			if (entityManagerFactory != null && entityManagerFactory.isOpen()) {
				entityManagerFactory.close();
			}
			entityManagerFactory = buildEntityManagerFactory();

			// register ourselves
			HbHelper.INSTANCE.register(this);

			setInitialized(true);

			setEventListeners();
		} finally {
			PackageRegistryProvider.getInstance().setThreadPackageRegistry(null);
		}
	}

	/** Build the mappings in the configuration */
	@Override
	protected void buildMappings() {
		getConfiguration().buildMappings();
	}

	/** Set the event listener, can be overridden, in this impl. it does nothing */
	@Override
	protected void setEventListeners() {
		final EMFInitializeCollectionEventListener eventListener = getExtensionManager().getExtension(
				EMFInitializeCollectionEventListener.class);
		EntityManagerFactory emf = getEntityManagerFactory();
		if (emf instanceof WrappedEntityManagerFactory) {
			emf = ((WrappedEntityManagerFactory) emf).getDelegate();
		}
		final ServiceRegistry serviceRegistry = ((SessionFactoryImpl) ((EntityManagerFactoryImpl) emf)
				.getSessionFactory()).getServiceRegistry();
		final EventListenerRegistry eventListenerRegistry = serviceRegistry
				.getService(EventListenerRegistry.class);
		eventListenerRegistry.appendListeners(EventType.INIT_COLLECTION, eventListener);

		if (isAuditing()) {
			auditProcessHandler = getExtensionManager().getExtension(
					AuditProcessHandler.class);
			auditProcessHandler.setDataStore(this);
			eventListenerRegistry.appendListeners(EventType.POST_DELETE, auditProcessHandler);
			eventListenerRegistry.appendListeners(EventType.POST_INSERT, auditProcessHandler);
			eventListenerRegistry.appendListeners(EventType.POST_UPDATE, auditProcessHandler);
			eventListenerRegistry.appendListeners(EventType.FLUSH, auditProcessHandler);
		}

	}

	/**
	 * Note the audit process handler is set in the {@link #setEventListeners()} method.
	 * 
	 * To override the auditprocess handler use Teneo's extension mechanism.
	 */
	public AuditProcessHandler getAuditProcessHandler() {
		return auditProcessHandler;
	}

	/** Sets the interceptor */
	@Override
	protected void setInterceptor() {
		if (getInterceptor() != null) {
			return;
		}
		final Interceptor interceptor = getHbContext().createInterceptor(getHibernateConfiguration(),
				getEntityNameStrategy());
		if (interceptor instanceof EMFInterceptor) {
			((EMFInterceptor) interceptor).setDataStore(this);
		}
		getConfiguration().setInterceptor(interceptor);
		setInterceptor(interceptor);
	}

	/** Returns a new ejb3 configuration object */
	protected Ejb3Configuration createConfiguration() {
		return new Ejb3Configuration();
	}

	/** Sets the properties in the Hibernate Configuration. */
	protected void setPropertiesInConfiguration() {
		Properties properties = getDataStoreProperties();
		if (properties != null) {
			setDefaultProperties(properties);
			// set this as this gives errors in the hibernate entity manager
			// see this bugzilla:
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=330855
			// Using HbEntityDataStore causes org.hibernate.MappingException:
			// Unknown entity:...
			if (!properties.containsKey("hibernate.ejb.metamodel.generation")) {
				properties.setProperty("hibernate.ejb.metamodel.generation", "disabled");
			}
			getConfiguration().addProperties(properties);
		}
	}

	/**
	 * Maps an ecore model of one ore more epackages into a hibernate xml String which is added to the
	 * passed configuration
	 */
	protected void mapModel() {
		if (getPersistenceOptions().isUseMappingFile()
				|| getPersistenceOptions().getMappingFilePath() != null) {
			if (log.isDebugEnabled()) {
				log.debug("Searching hbm files in class paths of epackages");
			}
			final String[] fileList = getMappingFileList();
			for (String element : fileList) {
				if (log.isDebugEnabled()) {
					log.debug("Adding file " + element + " to Hibernate Configuration");
				}
				final PersistenceFileProvider pfp = getExtensionManager().getExtension(
						PersistenceFileProvider.class);
				final InputStream is = pfp.getFileContent(this.getClass(), element);
				if (is == null) {
					throw new HbStoreException("Path to mapping file: " + element + " does not exist!");
				}
				getConfiguration().addInputStream(is);
			}
		} else {
			setMappingXML(mapEPackages());

			boolean hasEAVMapping = false;
			for (PAnnotatedEPackage aPackage : getPaModel().getPaEPackages()) {
				for (PAnnotatedEClass aClass : aPackage.getPaEClasses()) {
					if (aClass.getEavMapping() != null) {
						hasEAVMapping = true;
						break;
					}
				}
			}
			if (hasEAVMapping) {
				try {
					if (getPersistenceOptions().getEAVMappingFile() != null) {
						final PersistenceFileProvider pfp = getExtensionManager().getExtension(
								PersistenceFileProvider.class);
						final InputStream is = pfp.getFileContent(this.getClass(), getPersistenceOptions()
								.getEAVMappingFile());
						getConfiguration().addInputStream(processEAV(is));
						is.close();
					} else {
						final PersistenceFileProvider pfp = getExtensionManager().getExtension(
								PersistenceFileProvider.class);
						final InputStream is = pfp.getFileContent(EAVGenericIDUserType.class, "eav.hbm.xml");
						getConfiguration().addInputStream(processEAV(is));
						is.close();
					}
				} catch (IOException e) {
					throw new IllegalStateException(e);
				}
			}

			// TODO replace this
			final StringBufferInputStream is = new StringBufferInputStream(getMappingXML());
			getConfiguration().addInputStream(is);
		}
	}

	protected InputStream processEAV(InputStream is) {
		return new StringBufferInputStream(processEAVMapping(is));
	}

	/** Build the session factory */
	protected EntityManagerFactory buildEntityManagerFactory() {
		final EntityManagerFactory emf = getConfiguration().buildEntityManagerFactory();
		return new WrappedEntityManagerFactory(emf);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.emf.teneo.hibernate.HbDataStore#close()
	 */
	@Override
	public void close() {
		if (isInitialized()) {
			if (getEntityManagerFactory().isOpen()) {
				getEntityManagerFactory().close();
			}
			entityManagerFactory = null;
			setInitialized(false);
			// this will call the close method again but because the
			// datastore
			// is not initialized anymore it won't get here
			HbHelper.INSTANCE.deRegisterDataStore(this);
		}
		ejb3Configuration = null;
	}

	/**
	 * Note: returns an instance of the {@link WrappedEntityManagerFactory} class.
	 */
	public EntityManagerFactory getEntityManagerFactory() {
		if (!isInitialized()) {
			initialize();
		}
		assert (entityManagerFactory != null);
		return entityManagerFactory;
	}

	/** Return a new session wrapper */
	@Override
	public SessionWrapper createSessionWrapper() {
		return new HbEntityManagerWrapper(this);
	}

	/**
	 * @return the ejbConfiguration
	 */
	public Ejb3Configuration getConfiguration() {
		if (ejb3Configuration == null) {
			ejb3Configuration = createConfiguration();
		}
		return ejb3Configuration;
	}

	public void setConfiguration(Ejb3Configuration configuration) {
		ejb3Configuration = configuration;
	}

	/**
	 * @return the hbConfiguration
	 */
	@Override
	public Configuration getHibernateConfiguration() {
		return getConfiguration().getHibernateConfiguration();
	}

	/** Return the Classmappings as an iterator */
	@Override
	public Iterator<?> getClassMappings() {
		return getConfiguration().getClassMappings();
	}

	/** Is added for interface compliance with HbDataStore, should not be used */
	@Override
	public SessionFactory getSessionFactory() {
		final EntityManagerFactoryImpl entityManagerFactoryImpl;
		if (getEntityManagerFactory() instanceof WrappedEntityManagerFactory) {
			entityManagerFactoryImpl = (EntityManagerFactoryImpl) ((WrappedEntityManagerFactory) getEntityManagerFactory())
					.getDelegate();
		} else {
			entityManagerFactoryImpl = (EntityManagerFactoryImpl) getEntityManagerFactory();
		}
		return entityManagerFactoryImpl.getSessionFactory();
	}

	/**
	 * Note: returns the {@link WrappedEntityManager} class.
	 */
	public EntityManager createEntityManager() {
		return getEntityManagerFactory().createEntityManager();
	}

	/**
	 * Note: returns the {@link WrappedEntityManager} class.
	 */
	@SuppressWarnings("rawtypes")
	public EntityManager createEntityManager(Map arg0) {
		return getEntityManagerFactory().createEntityManager(arg0);
	}

	public boolean isOpen() {
		return getEntityManagerFactory().isOpen();
	}

	public Cache getCache() {
		return getEntityManagerFactory().getCache();
	}

	public CriteriaBuilder getCriteriaBuilder() {
		return getEntityManagerFactory().getCriteriaBuilder();
	}

	public Metamodel getMetamodel() {
		return getEntityManagerFactory().getMetamodel();
	}

	public PersistenceUnitUtil getPersistenceUnitUtil() {
		return getEntityManagerFactory().getPersistenceUnitUtil();
	}

	public Map<String, Object> getProperties() {
		return getEntityManagerFactory().getProperties();
	}

	/**
	 * The HbEntityDataStore uses a wrapped entity manager factory and wrapped entity manager to work
	 * around an issue that the Hibernate entity manager/ query implementation does not resolve query
	 * parameters of the EntityType correctly. It determines a wrong type. See the statement about
	 * this in the javadoc of the Hibernate {@link EntityType#getReturnedClass()} method.
	 * 
	 * To get to the original Hibernate entity manager use the
	 * {@link WrappedEntityManagerFactory#getDelegate()} method.
	 * 
	 * @author mtaal
	 */
	public class WrappedEntityManagerFactory implements EntityManagerFactory {
		private EntityManagerFactory delegate;

		public WrappedEntityManagerFactory(EntityManagerFactory emf) {
			delegate = emf;
		}

		public EntityManagerFactory getDelegate() {
			return delegate;
		}

		public void setDelegate(EntityManagerFactory delegate) {
			this.delegate = delegate;
		}

		public void close() {
			delegate.close();
		}

		public EntityManager createEntityManager() {
			EntityManager em = delegate.createEntityManager();
			return new WrappedEntityManager(em);
		}

		public EntityManager createEntityManager(@SuppressWarnings("rawtypes") Map map) {
			EntityManager em = delegate.createEntityManager(map);
			return new WrappedEntityManager(em);
		}

		public Cache getCache() {
			return delegate.getCache();
		}

		public CriteriaBuilder getCriteriaBuilder() {
			return delegate.getCriteriaBuilder();
		}

		public Metamodel getMetamodel() {
			return delegate.getMetamodel();
		}

		public PersistenceUnitUtil getPersistenceUnitUtil() {
			return delegate.getPersistenceUnitUtil();
		}

		public Map<String, Object> getProperties() {
			return delegate.getProperties();
		}

		public boolean isOpen() {
			return delegate.isOpen();
		}

		// JPA 2.1
		// public <T> void addNamedEntityGraph(String arg0, EntityGraph<T> arg1) {
		// delegate.addNamedEntityGraph(arg0, arg1);
		// }

		public void addNamedQuery(String arg0, Query arg1) {
			delegate.addNamedQuery(arg0, arg1);
		}

		public EntityManager createEntityManager(SynchronizationType arg0) {
			return delegate.createEntityManager(arg0);
		}

		public EntityManager createEntityManager(SynchronizationType arg0,
				@SuppressWarnings("rawtypes") Map arg1) {
			return delegate.createEntityManager(arg0, arg1);
		}

		public <T> T unwrap(Class<T> arg0) {
			return delegate.unwrap(arg0);
		}
	}

	/**
	 * See {@link WrappedEntityManagerFactory} for a description why this class is needed.
	 * 
	 * To get to the original Hibernate entity manager use the
	 * {@link WrappedEntityManager#getDelegateEntityManager()} method.
	 * 
	 * @author mtaal
	 * 
	 */
	public class WrappedEntityManager implements EntityManager {
		private EntityManager delegateEntityManager;

		public WrappedEntityManager(EntityManager em) {
			delegateEntityManager = em;
		}

		public void clear() {
			delegateEntityManager.clear();
		}

		public void close() {
			if (delegateEntityManager.isOpen()) {
				delegateEntityManager.close();
			}
		}

		public boolean contains(Object arg0) {
			return delegateEntityManager.contains(arg0);
		}

		@SuppressWarnings("unchecked")
		public <T> TypedQuery<T> createNamedQuery(String arg0, Class<T> arg1) {
			return (TypedQuery<T>) HbEntityDataStore.this
					.repairParameterJavaType((QueryImpl<?>) delegateEntityManager
							.createNamedQuery(arg0, arg1));
		}

		public Query createNamedQuery(String arg0) {
			return (Query) HbEntityDataStore.this
					.repairParameterJavaType((QueryImpl<?>) delegateEntityManager.createNamedQuery(arg0));
		}

		public Query createNativeQuery(String arg0, @SuppressWarnings("rawtypes") Class arg1) {
			return (Query) HbEntityDataStore.this
					.repairParameterJavaType((QueryImpl<?>) delegateEntityManager.createNativeQuery(arg0,
							arg1));
		}

		public Query createNativeQuery(String arg0, String arg1) {
			return (Query) HbEntityDataStore.this
					.repairParameterJavaType((QueryImpl<?>) delegateEntityManager.createNativeQuery(arg0,
							arg1));
		}

		public Query createNativeQuery(String arg0) {
			return (Query) HbEntityDataStore.this
					.repairParameterJavaType((QueryImpl<?>) delegateEntityManager.createNativeQuery(arg0));
		}

		@SuppressWarnings("unchecked")
		public <T> TypedQuery<T> createQuery(CriteriaQuery<T> arg0) {
			return (TypedQuery<T>) HbEntityDataStore.this
					.repairParameterJavaType((QueryImpl<?>) delegateEntityManager.createQuery(arg0));
		}

		@SuppressWarnings("unchecked")
		public <T> TypedQuery<T> createQuery(String arg0, Class<T> arg1) {
			return (TypedQuery<T>) HbEntityDataStore.this
					.repairParameterJavaType((QueryImpl<?>) delegateEntityManager.createQuery(arg0, arg1));
		}

		public Query createQuery(String arg0) {
			return (Query) HbEntityDataStore.this
					.repairParameterJavaType((QueryImpl<?>) delegateEntityManager.createQuery(arg0));
		}

		public void detach(Object arg0) {
			delegateEntityManager.detach(arg0);
		}

		public <T> T find(Class<T> arg0, Object arg1, LockModeType arg2, Map<String, Object> arg3) {
			return delegateEntityManager.find(arg0, arg1, arg2, arg3);
		}

		public <T> T find(Class<T> arg0, Object arg1, LockModeType arg2) {
			return delegateEntityManager.find(arg0, arg1, arg2);
		}

		public <T> T find(Class<T> arg0, Object arg1, Map<String, Object> arg2) {
			return delegateEntityManager.find(arg0, arg1, arg2);
		}

		public <T> T find(Class<T> arg0, Object arg1) {
			return delegateEntityManager.find(arg0, arg1);
		}

		public void flush() {
			delegateEntityManager.flush();
		}

		public CriteriaBuilder getCriteriaBuilder() {
			return delegateEntityManager.getCriteriaBuilder();
		}

		public Object getDelegate() {
			return delegateEntityManager.getDelegate();
		}

		public EntityManagerFactory getEntityManagerFactory() {
			return delegateEntityManager.getEntityManagerFactory();
		}

		public FlushModeType getFlushMode() {
			return delegateEntityManager.getFlushMode();
		}

		public LockModeType getLockMode(Object arg0) {
			return delegateEntityManager.getLockMode(arg0);
		}

		public Metamodel getMetamodel() {
			return delegateEntityManager.getMetamodel();
		}

		public Map<String, Object> getProperties() {
			return delegateEntityManager.getProperties();
		}

		public <T> T getReference(Class<T> arg0, Object arg1) {
			return delegateEntityManager.getReference(arg0, arg1);
		}

		public EntityTransaction getTransaction() {
			return delegateEntityManager.getTransaction();
		}

		public boolean isOpen() {
			return delegateEntityManager.isOpen();
		}

		public void joinTransaction() {
			delegateEntityManager.joinTransaction();
		}

		public void lock(Object arg0, LockModeType arg1, Map<String, Object> arg2) {
			delegateEntityManager.lock(arg0, arg1, arg2);
		}

		public void lock(Object arg0, LockModeType arg1) {
			delegateEntityManager.lock(arg0, arg1);
		}

		public <T> T merge(T arg0) {
			return delegateEntityManager.merge(arg0);
		}

		public void persist(Object arg0) {
			delegateEntityManager.persist(arg0);
		}

		public void refresh(Object arg0, LockModeType arg1, Map<String, Object> arg2) {
			delegateEntityManager.refresh(arg0, arg1, arg2);
		}

		public void refresh(Object arg0, LockModeType arg1) {
			delegateEntityManager.refresh(arg0, arg1);
		}

		public void refresh(Object arg0, Map<String, Object> arg1) {
			delegateEntityManager.refresh(arg0, arg1);
		}

		public void refresh(Object arg0) {
			delegateEntityManager.refresh(arg0);
		}

		public void remove(Object arg0) {
			delegateEntityManager.remove(arg0);
		}

		public void setFlushMode(FlushModeType arg0) {
			delegateEntityManager.setFlushMode(arg0);
		}

		public void setProperty(String arg0, Object arg1) {
			delegateEntityManager.setProperty(arg0, arg1);
		}

		public <T> T unwrap(Class<T> arg0) {
			return delegateEntityManager.unwrap(arg0);
		}

		public EntityManager getDelegateEntityManager() {
			return delegateEntityManager;
		}

		public void setDelegateEntityManager(EntityManager delegateEntityManager) {
			this.delegateEntityManager = delegateEntityManager;
		}

		// JPA 2.1
		// public <T> EntityGraph<T> createEntityGraph(Class<T> arg0) {
		// return delegateEntityManager.createEntityGraph(arg0);
		// }
		//
		// public EntityGraph<?> createEntityGraph(String arg0) {
		// return delegateEntityManager.createEntityGraph(arg0);
		// }

		public StoredProcedureQuery createNamedStoredProcedureQuery(String arg0) {
			return delegateEntityManager.createNamedStoredProcedureQuery(arg0);
		}

		public Query createQuery(@SuppressWarnings("rawtypes") CriteriaUpdate arg0) {
			return delegateEntityManager.createQuery(arg0);
		}

		public Query createQuery(@SuppressWarnings("rawtypes") CriteriaDelete arg0) {
			return delegateEntityManager.createQuery(arg0);
		}

		public StoredProcedureQuery createStoredProcedureQuery(String arg0) {
			return delegateEntityManager.createStoredProcedureQuery(arg0);
		}

		public StoredProcedureQuery createStoredProcedureQuery(String arg0,
				@SuppressWarnings("rawtypes") Class... arg1) {
			return delegateEntityManager.createStoredProcedureQuery(arg0, arg1);
		}

		public StoredProcedureQuery createStoredProcedureQuery(String arg0, String... arg1) {
			return delegateEntityManager.createStoredProcedureQuery(arg0, arg1);
		}

		// JPA 2.1
		// public EntityGraph<?> getEntityGraph(String arg0) {
		// return delegateEntityManager.getEntityGraph(arg0);
		// }
		//
		// public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> arg0) {
		// return delegateEntityManager.getEntityGraphs(arg0);
		// }

		public boolean isJoinedToTransaction() {
			return delegateEntityManager.isJoinedToTransaction();
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected QueryImpl<?> repairParameterJavaType(QueryImpl<?> query) {
		try {
			final Set<Parameter<?>> repairedParameters = new HashSet<Parameter<?>>();
			final Object parametersObject = getQueryParametersField().get(query);
			final AbstractQueryImpl queryImpl = AbstractQueryImpl.class.cast(query.getHibernateQuery());
			for (Parameter<?> parameter : (Collection<Parameter>) parametersObject) {
				if (Map.class == parameter.getParameterType()) {
					final Type type;
					if (parameter.getName() != null) {
						// repair these ones
						final NamedParameterDescriptor descriptor = queryImpl.getParameterMetadata()
								.getNamedParameterDescriptor(parameter.getName());
						type = descriptor.getExpectedType();
					} else {
						type = queryImpl.getParameterMetadata().getOrdinalParameterExpectedType(
								parameter.getPosition());
					}
					if (type instanceof EntityType) {
						final Parameter<?> param = new ParameterImpl(parameter.getName(),
								parameter.getPosition(), Object.class);
						repairedParameters.add(param);
						// final EntityType entityType = (EntityType) type;
						// final String entityName = entityType
						// .getAssociatedEntityName();
						// final EClass eClass = HbEntityDataStore.this
						// .getEntityNameStrategy().toEClass(entityName);

					} else {
						repairedParameters.add(parameter);
					}
				} else {
					repairedParameters.add(parameter);
				}
			}
			getQueryParametersField().set(query, repairedParameters);
			return query;
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}

	protected Field getQueryParametersField() throws Exception {
		if (queryParametersField != null) {
			return queryParametersField;
		}
		Field field = QueryImpl.class.getDeclaredField("parameters");
		field.setAccessible(true);
		return field;
	}

	@SuppressWarnings("rawtypes")
	private static class ParameterImpl implements Parameter {
		private String name;
		private Integer position;
		private Class<?> javaClass;

		ParameterImpl(String name, Integer position, Class<?> clz) {
			this.name = name;
			this.position = position;
			this.javaClass = clz;
		}

		public Class<?> getParameterType() {
			return javaClass;
		}

		public String getName() {
			return name;
		}

		public Integer getPosition() {
			return position;
		}
	}

	// JPA 2.1
	// public <T> void addNamedEntityGraph(String arg0, EntityGraph<T> arg1) {
	// getEntityManagerFactory().addNamedEntityGraph(arg0, arg1);
	// }
	//
	// public void addNamedQuery(String arg0, Query arg1) {
	// getEntityManagerFactory().addNamedQuery(arg0, arg1);
	// }

	public EntityManager createEntityManager(SynchronizationType arg0) {
		return getEntityManagerFactory().createEntityManager(arg0);
	}

	public EntityManager createEntityManager(SynchronizationType arg0,
			@SuppressWarnings("rawtypes") Map arg1) {
		return getEntityManagerFactory().createEntityManager(arg0, arg1);
	}

	public <T> T unwrap(Class<T> arg0) {
		return getEntityManagerFactory().unwrap(arg0);
	}

}

Back to the top