-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
EntityManagerFactoryImpl.java
executable file
·278 lines (241 loc) · 10.1 KB
/
EntityManagerFactoryImpl.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
/*
* Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.persistence.Cache;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContextType;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.metamodel.Metamodel;
import javax.persistence.spi.LoadState;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.internal.EntityManagerFactoryRegistry;
import org.hibernate.ejb.metamodel.MetamodelImpl;
import org.hibernate.ejb.util.PersistenceUtilHelper;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.UUIDGenerator;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.service.ServiceRegistry;
/**
* Actual Hibernate implementation of {@link javax.persistence.EntityManagerFactory}.
*
* @author Gavin King
* @author Emmanuel Bernard
* @author Steve Ebersole
*/
public class EntityManagerFactoryImpl implements HibernateEntityManagerFactory {
private static final long serialVersionUID = 5423543L;
private static final IdentifierGenerator UUID_GENERATOR = UUIDGenerator.buildSessionFactoryUniqueIdentifierGenerator();
private final transient SessionFactory sessionFactory;
private final transient PersistenceUnitTransactionType transactionType;
private final transient boolean discardOnClose;
private final transient Class sessionInterceptorClass;
private final transient CriteriaBuilderImpl criteriaBuilder;
private final transient Metamodel metamodel;
private final transient HibernatePersistenceUnitUtil util;
private final transient Map<String,Object> properties;
private final String entityManagerFactoryName;
private final transient PersistenceUtilHelper.MetadataCache cache = new PersistenceUtilHelper.MetadataCache();
@SuppressWarnings( "unchecked" )
public EntityManagerFactoryImpl(
PersistenceUnitTransactionType transactionType,
boolean discardOnClose,
Class sessionInterceptorClass,
Configuration cfg,
ServiceRegistry serviceRegistry,
String persistenceUnitName) {
this.sessionFactory = cfg.buildSessionFactory( serviceRegistry );
this.transactionType = transactionType;
this.discardOnClose = discardOnClose;
this.sessionInterceptorClass = sessionInterceptorClass;
final Iterator<PersistentClass> classes = cfg.getClassMappings();
//a safe guard till we are confident that metamodel is well tested
// disabled: dont create metamodel
// ignoreUnsupported: create metamodel, but ignore unsupported/unknown annotations (like @Any) HHH-6589
final String ejbMetamodelGenerationProperty = cfg.getProperty( "hibernate.ejb.metamodel.generation" );
if ( !"disabled".equalsIgnoreCase( ejbMetamodelGenerationProperty ) ) {
this.metamodel = MetamodelImpl.buildMetamodel( classes, ( SessionFactoryImplementor ) sessionFactory, "ignoreUnsupported".equalsIgnoreCase( ejbMetamodelGenerationProperty ));
}
else {
this.metamodel = null;
}
this.criteriaBuilder = new CriteriaBuilderImpl( this );
this.util = new HibernatePersistenceUnitUtil( this );
HashMap<String,Object> props = new HashMap<String, Object>();
addAll( props, ( (SessionFactoryImplementor) sessionFactory ).getProperties() );
addAll( props, cfg.getProperties() );
this.properties = Collections.unmodifiableMap( props );
String entityManagerFactoryName = (String)this.properties.get(AvailableSettings.ENTITY_MANAGER_FACTORY_NAME);
if (entityManagerFactoryName == null) {
entityManagerFactoryName = persistenceUnitName;
}
if (entityManagerFactoryName == null) {
entityManagerFactoryName = (String) UUID_GENERATOR.generate(null, null);
}
this.entityManagerFactoryName = entityManagerFactoryName;
EntityManagerFactoryRegistry.INSTANCE.addEntityManagerFactory(entityManagerFactoryName, this);
}
private static void addAll(HashMap<String, Object> propertyMap, Properties properties) {
for ( Map.Entry entry : properties.entrySet() ) {
if ( String.class.isInstance( entry.getKey() ) ) {
propertyMap.put( (String)entry.getKey(), entry.getValue() );
}
}
}
public EntityManager createEntityManager() {
return createEntityManager( null );
}
public EntityManager createEntityManager(Map map) {
//TODO support discardOnClose, persistencecontexttype?, interceptor,
return new EntityManagerImpl(
this, PersistenceContextType.EXTENDED, transactionType,
discardOnClose, sessionInterceptorClass, map
);
}
public CriteriaBuilder getCriteriaBuilder() {
return criteriaBuilder;
}
public Metamodel getMetamodel() {
return metamodel;
}
public void close() {
sessionFactory.close();
EntityManagerFactoryRegistry.INSTANCE.removeEntityManagerFactory(entityManagerFactoryName, this);
}
public Map<String, Object> getProperties() {
return properties;
}
public Cache getCache() {
// TODO : cache the cache reference?
if ( ! isOpen() ) {
throw new IllegalStateException("EntityManagerFactory is closed");
}
return new JPACache( sessionFactory );
}
public PersistenceUnitUtil getPersistenceUnitUtil() {
if ( ! isOpen() ) {
throw new IllegalStateException("EntityManagerFactory is closed");
}
return util;
}
public boolean isOpen() {
return ! sessionFactory.isClosed();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public String getEntityManagerFactoryName() {
return entityManagerFactoryName;
}
private static class JPACache implements Cache {
private SessionFactory sessionFactory;
private JPACache(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public boolean contains(Class entityClass, Object identifier) {
return sessionFactory.getCache().containsEntity( entityClass, ( Serializable ) identifier );
}
public void evict(Class entityClass, Object identifier) {
sessionFactory.getCache().evictEntity( entityClass, ( Serializable ) identifier );
}
public void evict(Class entityClass) {
sessionFactory.getCache().evictEntityRegion( entityClass );
}
public void evictAll() {
sessionFactory.getCache().evictEntityRegions();
// TODO : if we want to allow an optional clearing of all cache data, the additional calls would be:
// sessionFactory.getCache().evictCollectionRegions();
// sessionFactory.getCache().evictQueryRegions();
}
}
private static EntityManagerFactory getNamedEntityManagerFactory(String entityManagerFactoryName) throws InvalidObjectException {
Object result = EntityManagerFactoryRegistry.INSTANCE.getNamedEntityManagerFactory(entityManagerFactoryName);
if ( result == null ) {
throw new InvalidObjectException( "could not resolve entity manager factory during entity manager deserialization [name=" + entityManagerFactoryName + "]" );
}
return (EntityManagerFactory)result;
}
private void writeObject(ObjectOutputStream oos) throws IOException {
if (entityManagerFactoryName == null) {
throw new InvalidObjectException( "could not serialize entity manager factory with null entityManagerFactoryName" );
}
oos.defaultWriteObject();
}
/**
* After deserialization of an EntityManagerFactory, this is invoked to return the EntityManagerFactory instance
* that is already in use rather than a cloned copy of the object.
*
* @return
* @throws InvalidObjectException
*/
private Object readResolve() throws InvalidObjectException {
return getNamedEntityManagerFactory(entityManagerFactoryName);
}
private static class HibernatePersistenceUnitUtil implements PersistenceUnitUtil, Serializable {
private final HibernateEntityManagerFactory emf;
private transient PersistenceUtilHelper.MetadataCache cache;
private HibernatePersistenceUnitUtil(EntityManagerFactoryImpl emf) {
this.emf = emf;
this.cache = emf.cache;
}
public boolean isLoaded(Object entity, String attributeName) {
LoadState state = PersistenceUtilHelper.isLoadedWithoutReference( entity, attributeName, cache );
if (state == LoadState.LOADED) {
return true;
}
else if (state == LoadState.NOT_LOADED ) {
return false;
}
else {
return PersistenceUtilHelper.isLoadedWithReference( entity, attributeName, cache ) != LoadState.NOT_LOADED;
}
}
public boolean isLoaded(Object entity) {
return PersistenceUtilHelper.isLoaded( entity ) != LoadState.NOT_LOADED;
}
public Object getIdentifier(Object entity) {
final Class entityClass = Hibernate.getClass( entity );
final ClassMetadata classMetadata = emf.getSessionFactory().getClassMetadata( entityClass );
if (classMetadata == null) {
throw new IllegalArgumentException( entityClass + " is not an entity" );
}
//TODO does that work for @IdClass?
return classMetadata.getIdentifier( entity );
}
}
}