2 * Hibernate, Relational Persistence for Idiomatic Java
4 * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
5 * indicated by the @author tags or express copyright attribution
6 * statements applied by the authors. All third-party contributions are
7 * distributed under license by Red Hat Inc.
9 * This copyrighted material is made available to anyone wishing to use, modify,
10 * copy, or redistribute it subject to the terms and conditions of the GNU
11 * Lesser General Public License, as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this distribution; if not, write to:
20 * Free Software Foundation, Inc.
21 * 51 Franklin Street, Fifth Floor
22 * Boston, MA 02110-1301 USA
24 package org
.hibernate
.proxy
;
26 import java
.io
.Serializable
;
28 import javax
.naming
.NamingException
;
30 import org
.hibernate
.HibernateException
;
31 import org
.hibernate
.LazyInitializationException
;
32 import org
.hibernate
.Session
;
33 import org
.hibernate
.SessionException
;
34 import org
.hibernate
.TransientObjectException
;
35 import org
.hibernate
.engine
.spi
.EntityKey
;
36 import org
.hibernate
.engine
.spi
.SessionFactoryImplementor
;
37 import org
.hibernate
.engine
.spi
.SessionImplementor
;
38 import org
.hibernate
.internal
.SessionFactoryRegistry
;
39 import org
.hibernate
.persister
.entity
.EntityPersister
;
40 import org
.jboss
.logging
.Logger
;
42 import eu
.etaxonomy
.cdm
.api
.application
.CdmApplicationRemoteConfiguration
;
43 import eu
.etaxonomy
.cdm
.model
.common
.CdmBase
;
44 import eu
.etaxonomy
.taxeditor
.remoting
.cache
.ICachedCommonService
;
47 * Convenience base class for lazy initialization handlers. Centralizes the basic plumbing of doing lazy
48 * initialization freeing subclasses to acts as essentially adapters to their intended entity mode and/or
49 * proxy generation strategy.
53 public abstract class AbstractLazyInitializer
implements LazyInitializer
{
54 private static final Logger log
= Logger
.getLogger( AbstractLazyInitializer
.class );
56 private String entityName
;
57 private Serializable id
;
58 private Object target
;
59 private boolean initialized
;
60 private boolean readOnly
;
61 private boolean unwrap
;
62 private transient SessionImplementor session
;
63 private Boolean readOnlyBeforeAttachedToSession
;
65 private String sessionFactoryUuid
;
66 private boolean specjLazyLoad
= false;
69 * For serialization from the non-pojo initializers (HHH-3309)
71 protected AbstractLazyInitializer() {
77 * @param entityName The name of the entity being proxied.
78 * @param id The identifier of the entity being proxied.
79 * @param session The session owning the proxy.
81 protected AbstractLazyInitializer(String entityName
, Serializable id
, SessionImplementor session
) {
82 this.entityName
= entityName
;
84 // initialize other fields depending on session state
85 if ( session
== null ) {
89 setSession( session
);
94 public final String
getEntityName() {
99 public final Serializable
getIdentifier() {
104 public final void setIdentifier(Serializable id
) {
109 public final boolean isUninitialized() {
114 public final SessionImplementor
getSession() {
119 public final void setSession(SessionImplementor s
) throws HibernateException
{
120 if ( s
!= session
) {
121 // check for s == null first, since it is least expensive
125 else if ( isConnectedToSession() ) {
126 //TODO: perhaps this should be some other RuntimeException...
127 throw new HibernateException( "illegally attempted to associate a proxy with two open Sessions" );
132 if ( readOnlyBeforeAttachedToSession
== null ) {
133 // use the default read-only/modifiable setting
134 final EntityPersister persister
= s
.getFactory().getEntityPersister( entityName
);
135 setReadOnly( s
.getPersistenceContext().isDefaultReadOnly() || !persister
.isMutable() );
138 // use the read-only/modifiable setting indicated during deserialization
139 setReadOnly( readOnlyBeforeAttachedToSession
.booleanValue() );
140 readOnlyBeforeAttachedToSession
= null;
146 private static EntityKey
generateEntityKeyOrNull(Serializable id
, SessionImplementor s
, String entityName
) {
147 if ( id
== null || s
== null || entityName
== null ) {
150 return s
.generateEntityKey( id
, s
.getFactory().getEntityPersister( entityName
) );
154 public final void unsetSession() {
155 prepareForPossibleSpecialSpecjInitialization();
158 readOnlyBeforeAttachedToSession
= null;
162 public final void initialize() throws HibernateException
{
163 // In remoting we are sure that session is null
164 // both when using property paths and switching off conversations
165 if(session
== null && remoting
) {
168 if ( !initialized
) {
169 if ( specjLazyLoad
) {
170 specialSpecjInitialization();
172 else if ( session
== null ) {
173 throw new LazyInitializationException( "could not initialize proxy - no Session" );
175 else if ( !session
.isOpen() ) {
176 throw new LazyInitializationException( "could not initialize proxy - the owning Session was closed" );
178 else if ( !session
.isConnected() ) {
179 throw new LazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
182 target
= session
.immediateLoad( entityName
, id
);
192 protected void specialSpecjInitialization() {
193 if ( session
== null ) {
194 //we have a detached collection thats set to null, reattach
195 if ( sessionFactoryUuid
== null ) {
196 throw new LazyInitializationException( "could not initialize proxy - no Session" );
199 SessionFactoryImplementor sf
= (SessionFactoryImplementor
)
200 SessionFactoryRegistry
.INSTANCE
.getSessionFactory( sessionFactoryUuid
);
201 SessionImplementor session
= (SessionImplementor
) sf
.openSession();
203 // TODO: On the next major release, add an
204 // 'isJTA' or 'getTransactionFactory' method to Session.
205 boolean isJTA
= session
.getTransactionCoordinator()
206 .getTransactionContext().getTransactionEnvironment()
207 .getTransactionFactory()
208 .compatibleWithJtaSynchronization();
211 // Explicitly handle the transactions only if we're not in
212 // a JTA environment. A lazy loading temporary session can
213 // be created even if a current session and transaction are
214 // open (ex: session.clear() was used). We must prevent
215 // multiple transactions.
216 ( ( Session
) session
).beginTransaction();
220 target
= session
.immediateLoad( entityName
, id
);
223 // make sure the just opened temp session gets closed!
226 ( ( Session
) session
).getTransaction().commit();
228 ( (Session
) session
).close();
230 catch (Exception e
) {
231 log
.warn( "Unable to close temporary session used to load lazy proxy associated to no session" );
237 catch (Exception e
) {
239 throw new LazyInitializationException( e
.getMessage() );
242 else if ( session
.isOpen() && session
.isConnected() ) {
243 target
= session
.immediateLoad( entityName
, id
);
248 throw new LazyInitializationException( "could not initialize proxy - Session was closed or disced" );
252 protected void prepareForPossibleSpecialSpecjInitialization() {
253 if ( session
!= null ) {
254 specjLazyLoad
= session
.getFactory().getSettings().isInitializeLazyStateOutsideTransactionsEnabled();
256 if ( specjLazyLoad
&& sessionFactoryUuid
== null ) {
258 sessionFactoryUuid
= (String
) session
.getFactory().getReference().get( "uuid" ).getContent();
260 catch (NamingException e
) {
261 //not much we can do if this fails...
267 private void checkTargetState() {
269 if ( target
== null ) {
270 getSession().getFactory().getEntityNotFoundDelegate().handleEntityNotFound( entityName
, id
);
276 * Getter for property 'connectedToSession'.
278 * @return Value for property 'connectedToSession'.
280 protected final boolean isConnectedToSession() {
281 return getProxyOrNull() != null;
284 private Object
getProxyOrNull() {
285 final EntityKey entityKey
= generateEntityKeyOrNull( getIdentifier(), session
, getEntityName() );
286 if ( entityKey
!= null && session
!= null && session
.isOpen() ) {
287 return session
.getPersistenceContext().getProxy( entityKey
);
293 public final Object
getImplementation() {
299 public final void setImplementation(Object target
) {
300 this.target
= target
;
305 public final Object
getImplementation(SessionImplementor s
) throws HibernateException
{
306 final EntityKey entityKey
= generateEntityKeyOrNull( getIdentifier(), s
, getEntityName() );
307 return (entityKey
== null ?
null : s
.getPersistenceContext().getEntity( entityKey
));
311 * Getter for property 'target'.
313 * Same as {@link #getImplementation()} except that this method will not force initialization.
315 * @return Value for property 'target'.
317 protected final Object
getTarget() {
322 public final boolean isReadOnlySettingAvailable() {
323 return (session
!= null && !session
.isClosed());
326 private void errorIfReadOnlySettingNotAvailable() {
327 if ( session
== null ) {
328 throw new TransientObjectException(
329 "Proxy is detached (i.e, session is null). The read-only/modifiable setting is only accessible when the proxy is associated with an open session."
332 if ( session
.isClosed() ) {
333 throw new SessionException(
334 "Session is closed. The read-only/modifiable setting is only accessible when the proxy is associated with an open session."
340 public final boolean isReadOnly() {
341 errorIfReadOnlySettingNotAvailable();
346 public final void setReadOnly(boolean readOnly
) {
347 errorIfReadOnlySettingNotAvailable();
348 // only update if readOnly is different from current setting
349 if ( this.readOnly
!= readOnly
) {
350 final EntityPersister persister
= session
.getFactory().getEntityPersister( entityName
);
351 if ( !persister
.isMutable() && !readOnly
) {
352 throw new IllegalStateException( "cannot make proxies for immutable entities modifiable" );
354 this.readOnly
= readOnly
;
356 EntityKey key
= generateEntityKeyOrNull( getIdentifier(), session
, getEntityName() );
357 if ( key
!= null && session
.getPersistenceContext().containsEntity( key
) ) {
358 session
.getPersistenceContext().setReadOnly( target
, readOnly
);
365 * Get the read-only/modifiable setting that should be put in affect when it is
366 * attached to a session.
368 * This method should only be called during serialization when read-only/modifiable setting
369 * is not available (i.e., isReadOnlySettingAvailable() == false)
371 * @return null, if the default setting should be used;
372 * true, for read-only;
373 * false, for modifiable
375 * @throws IllegalStateException if isReadOnlySettingAvailable() == true
377 protected final Boolean
isReadOnlyBeforeAttachedToSession() {
378 if ( isReadOnlySettingAvailable() ) {
379 throw new IllegalStateException(
380 "Cannot call isReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
383 return readOnlyBeforeAttachedToSession
;
387 * Set the read-only/modifiable setting that should be put in affect when it is
388 * attached to a session.
390 * This method should only be called during deserialization, before associating
391 * the proxy with a session.
393 * @param readOnlyBeforeAttachedToSession, the read-only/modifiable setting to use when
394 * associated with a session; null indicates that the default should be used.
396 * @throws IllegalStateException if isReadOnlySettingAvailable() == true
398 /* package-private */
399 final void setReadOnlyBeforeAttachedToSession(Boolean readOnlyBeforeAttachedToSession
) {
400 if ( isReadOnlySettingAvailable() ) {
401 throw new IllegalStateException(
402 "Cannot call setReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
405 this.readOnlyBeforeAttachedToSession
= readOnlyBeforeAttachedToSession
;
409 public boolean isUnwrap() {
414 public void setUnwrap(boolean unwrap
) {
415 this.unwrap
= unwrap
;
418 /** Below is section of code which makes remote service calls */
420 private static CdmApplicationRemoteConfiguration configuration
;
421 private static boolean remoting
= false;
423 public static void setConfiguration(CdmApplicationRemoteConfiguration conf
) {
425 configuration
= conf
;
429 private void remoteInitialize() {
432 int classid
= ((Integer
)getIdentifier()).intValue();
433 log
.info("--> Remote Lazy Initializing Object " + getEntityName() + " with id " + classid
);
436 clazz
= Class
.forName(getEntityName());
437 } catch (ClassNotFoundException e
) {
438 throw new HibernateException("Class for " + getEntityName() + " not found", e
);
440 if(configuration
== null) {
441 throw new HibernateException("CdmApplicationRemoteConfiguration not initialized (null)");
443 ICachedCommonService cachedCommonService
= configuration
.getCachedCommonService();
444 if(cachedCommonService
== null) {
445 throw new HibernateException("commonService not initialized (null)");
448 CdmBase cdmBase
= cachedCommonService
.find(clazz
,classid
);
449 setImplementation(cdmBase
);
454 public static boolean isInitialized(AbstractLazyInitializer obj
) {
455 return obj
.initialized
;