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
;
41 import org
.springframework
.beans
.factory
.annotation
.Autowire
;
42 import org
.springframework
.beans
.factory
.annotation
.Configurable
;
43 import org
.springframework
.stereotype
.Component
;
45 import eu
.etaxonomy
.cdm
.api
.application
.ICdmApplicationConfiguration
;
46 import eu
.etaxonomy
.cdm
.api
.service
.ICommonService
;
47 import eu
.etaxonomy
.cdm
.model
.common
.CdmBase
;
50 * Convenience base class for lazy initialization handlers. Centralizes the basic plumbing of doing lazy
51 * initialization freeing subclasses to acts as essentially adapters to their intended entity mode and/or
52 * proxy generation strategy.
57 @Configurable(dependencyCheck
= true,autowire
= Autowire
.BY_TYPE
)
58 public abstract class AbstractLazyInitializer
implements LazyInitializer
{
59 private static final Logger log
= Logger
.getLogger( AbstractLazyInitializer
.class );
61 private String entityName
;
62 private Serializable id
;
63 private Object target
;
64 private boolean initialized
;
65 private boolean readOnly
;
66 private boolean unwrap
;
67 private transient SessionImplementor session
;
68 private Boolean readOnlyBeforeAttachedToSession
;
70 private String sessionFactoryUuid
;
71 private boolean specjLazyLoad
= false;
74 * For serialization from the non-pojo initializers (HHH-3309)
76 protected AbstractLazyInitializer() {
82 * @param entityName The name of the entity being proxied.
83 * @param id The identifier of the entity being proxied.
84 * @param session The session owning the proxy.
86 protected AbstractLazyInitializer(String entityName
, Serializable id
, SessionImplementor session
) {
87 this.entityName
= entityName
;
89 // initialize other fields depending on session state
90 if ( session
== null ) {
94 setSession( session
);
99 public final String
getEntityName() {
104 public final Serializable
getIdentifier() {
109 public final void setIdentifier(Serializable id
) {
114 public final boolean isUninitialized() {
119 public final SessionImplementor
getSession() {
124 public final void setSession(SessionImplementor s
) throws HibernateException
{
125 if ( s
!= session
) {
126 // check for s == null first, since it is least expensive
130 else if ( isConnectedToSession() ) {
131 //TODO: perhaps this should be some other RuntimeException...
132 throw new HibernateException( "illegally attempted to associate a proxy with two open Sessions" );
137 if ( readOnlyBeforeAttachedToSession
== null ) {
138 // use the default read-only/modifiable setting
139 final EntityPersister persister
= s
.getFactory().getEntityPersister( entityName
);
140 setReadOnly( s
.getPersistenceContext().isDefaultReadOnly() || !persister
.isMutable() );
143 // use the read-only/modifiable setting indicated during deserialization
144 setReadOnly( readOnlyBeforeAttachedToSession
.booleanValue() );
145 readOnlyBeforeAttachedToSession
= null;
151 private static EntityKey
generateEntityKeyOrNull(Serializable id
, SessionImplementor s
, String entityName
) {
152 if ( id
== null || s
== null || entityName
== null ) {
155 return s
.generateEntityKey( id
, s
.getFactory().getEntityPersister( entityName
) );
159 public final void unsetSession() {
160 prepareForPossibleSpecialSpecjInitialization();
163 readOnlyBeforeAttachedToSession
= null;
167 public final void initialize() throws HibernateException
{
168 // In remoting we are sure that session is null
169 // both when using property paths and switching off conversations
170 if(session
== null) {
173 if ( !initialized
) {
174 if ( specjLazyLoad
) {
175 specialSpecjInitialization();
177 else if ( session
== null ) {
178 throw new LazyInitializationException( "could not initialize proxy - no Session" );
180 else if ( !session
.isOpen() ) {
181 throw new LazyInitializationException( "could not initialize proxy - the owning Session was closed" );
183 else if ( !session
.isConnected() ) {
184 throw new LazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
187 target
= session
.immediateLoad( entityName
, id
);
197 protected void specialSpecjInitialization() {
198 if ( session
== null ) {
199 //we have a detached collection thats set to null, reattach
200 if ( sessionFactoryUuid
== null ) {
201 throw new LazyInitializationException( "could not initialize proxy - no Session" );
204 SessionFactoryImplementor sf
= (SessionFactoryImplementor
)
205 SessionFactoryRegistry
.INSTANCE
.getSessionFactory( sessionFactoryUuid
);
206 SessionImplementor session
= (SessionImplementor
) sf
.openSession();
208 // TODO: On the next major release, add an
209 // 'isJTA' or 'getTransactionFactory' method to Session.
210 boolean isJTA
= session
.getTransactionCoordinator()
211 .getTransactionContext().getTransactionEnvironment()
212 .getTransactionFactory()
213 .compatibleWithJtaSynchronization();
216 // Explicitly handle the transactions only if we're not in
217 // a JTA environment. A lazy loading temporary session can
218 // be created even if a current session and transaction are
219 // open (ex: session.clear() was used). We must prevent
220 // multiple transactions.
221 ( ( Session
) session
).beginTransaction();
225 target
= session
.immediateLoad( entityName
, id
);
228 // make sure the just opened temp session gets closed!
231 ( ( Session
) session
).getTransaction().commit();
233 ( (Session
) session
).close();
235 catch (Exception e
) {
236 log
.warn( "Unable to close temporary session used to load lazy proxy associated to no session" );
242 catch (Exception e
) {
244 throw new LazyInitializationException( e
.getMessage() );
247 else if ( session
.isOpen() && session
.isConnected() ) {
248 target
= session
.immediateLoad( entityName
, id
);
253 throw new LazyInitializationException( "could not initialize proxy - Session was closed or disced" );
257 protected void prepareForPossibleSpecialSpecjInitialization() {
258 if ( session
!= null ) {
259 specjLazyLoad
= session
.getFactory().getSettings().isInitializeLazyStateOutsideTransactionsEnabled();
261 if ( specjLazyLoad
&& sessionFactoryUuid
== null ) {
263 sessionFactoryUuid
= (String
) session
.getFactory().getReference().get( "uuid" ).getContent();
265 catch (NamingException e
) {
266 //not much we can do if this fails...
272 private void checkTargetState() {
274 if ( target
== null ) {
275 getSession().getFactory().getEntityNotFoundDelegate().handleEntityNotFound( entityName
, id
);
281 * Getter for property 'connectedToSession'.
283 * @return Value for property 'connectedToSession'.
285 protected final boolean isConnectedToSession() {
286 return getProxyOrNull() != null;
289 private Object
getProxyOrNull() {
290 final EntityKey entityKey
= generateEntityKeyOrNull( getIdentifier(), session
, getEntityName() );
291 if ( entityKey
!= null && session
!= null && session
.isOpen() ) {
292 return session
.getPersistenceContext().getProxy( entityKey
);
298 public final Object
getImplementation() {
304 public final void setImplementation(Object target
) {
305 this.target
= target
;
310 public final Object
getImplementation(SessionImplementor s
) throws HibernateException
{
311 final EntityKey entityKey
= generateEntityKeyOrNull( getIdentifier(), s
, getEntityName() );
312 return (entityKey
== null ?
null : s
.getPersistenceContext().getEntity( entityKey
));
316 * Getter for property 'target'.
318 * Same as {@link #getImplementation()} except that this method will not force initialization.
320 * @return Value for property 'target'.
322 protected final Object
getTarget() {
327 public final boolean isReadOnlySettingAvailable() {
328 return (session
!= null && !session
.isClosed());
331 private void errorIfReadOnlySettingNotAvailable() {
332 if ( session
== null ) {
333 throw new TransientObjectException(
334 "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."
337 if ( session
.isClosed() ) {
338 throw new SessionException(
339 "Session is closed. The read-only/modifiable setting is only accessible when the proxy is associated with an open session."
345 public final boolean isReadOnly() {
346 errorIfReadOnlySettingNotAvailable();
351 public final void setReadOnly(boolean readOnly
) {
352 errorIfReadOnlySettingNotAvailable();
353 // only update if readOnly is different from current setting
354 if ( this.readOnly
!= readOnly
) {
355 final EntityPersister persister
= session
.getFactory().getEntityPersister( entityName
);
356 if ( !persister
.isMutable() && !readOnly
) {
357 throw new IllegalStateException( "cannot make proxies for immutable entities modifiable" );
359 this.readOnly
= readOnly
;
361 EntityKey key
= generateEntityKeyOrNull( getIdentifier(), session
, getEntityName() );
362 if ( key
!= null && session
.getPersistenceContext().containsEntity( key
) ) {
363 session
.getPersistenceContext().setReadOnly( target
, readOnly
);
370 * Get the read-only/modifiable setting that should be put in affect when it is
371 * attached to a session.
373 * This method should only be called during serialization when read-only/modifiable setting
374 * is not available (i.e., isReadOnlySettingAvailable() == false)
376 * @return null, if the default setting should be used;
377 * true, for read-only;
378 * false, for modifiable
380 * @throws IllegalStateException if isReadOnlySettingAvailable() == true
382 protected final Boolean
isReadOnlyBeforeAttachedToSession() {
383 if ( isReadOnlySettingAvailable() ) {
384 throw new IllegalStateException(
385 "Cannot call isReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
388 return readOnlyBeforeAttachedToSession
;
392 * Set the read-only/modifiable setting that should be put in affect when it is
393 * attached to a session.
395 * This method should only be called during deserialization, before associating
396 * the proxy with a session.
398 * @param readOnlyBeforeAttachedToSession, the read-only/modifiable setting to use when
399 * associated with a session; null indicates that the default should be used.
401 * @throws IllegalStateException if isReadOnlySettingAvailable() == true
403 /* package-private */
404 final void setReadOnlyBeforeAttachedToSession(Boolean readOnlyBeforeAttachedToSession
) {
405 if ( isReadOnlySettingAvailable() ) {
406 throw new IllegalStateException(
407 "Cannot call setReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
410 this.readOnlyBeforeAttachedToSession
= readOnlyBeforeAttachedToSession
;
414 public boolean isUnwrap() {
419 public void setUnwrap(boolean unwrap
) {
420 this.unwrap
= unwrap
;
423 /** Below is section of code which makes remote service calls */
425 private static ICdmApplicationConfiguration configuration
;
427 public static void setConfiguration(ICdmApplicationConfiguration conf
) {
428 configuration
= conf
;
432 private void remoteInitialize() {
435 int classid
= ((Integer
)getIdentifier()).intValue();
436 System
.out
.print("--> Remote Lazy Initializing" + getEntityName() + " with id " + classid
);
439 clazz
= (Class
<?
extends CdmBase
>) Class
.forName(getEntityName());
440 } catch (ClassNotFoundException e
) {
441 throw new HibernateException("Class for " + getEntityName() + " not found", e
);
443 if(configuration
== null) {
444 throw new HibernateException("CdmApplicationRemoteConfiguration not initialized (null)");
446 ICommonService commonService
= configuration
.getCommonService();
447 if(commonService
== null) {
448 throw new HibernateException("commonService not initialized (null)");
451 CdmBase cdmBase
= CdmBase
.deproxy(commonService
.find(clazz
,classid
),clazz
);
452 setImplementation(cdmBase
);
453 System
.out
.println("....Done");