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
.Configurable
;
44 * Convenience base class for lazy initialization handlers. Centralizes the basic plumbing of doing lazy
45 * initialization freeing subclasses to acts as essentially adapters to their intended entity mode and/or
46 * proxy generation strategy.
50 @Configurable(dependencyCheck
= true)
51 public abstract class AbstractLazyInitializer
implements LazyInitializer
{
52 private static final Logger log
= Logger
.getLogger( AbstractLazyInitializer
.class );
54 private String entityName
;
55 private Serializable id
;
56 private Object target
;
57 private boolean initialized
;
58 private boolean readOnly
;
59 private boolean unwrap
;
60 private transient SessionImplementor session
;
61 private Boolean readOnlyBeforeAttachedToSession
;
63 private String sessionFactoryUuid
;
64 private boolean specjLazyLoad
= false;
67 * For serialization from the non-pojo initializers (HHH-3309)
69 protected AbstractLazyInitializer() {
75 * @param entityName The name of the entity being proxied.
76 * @param id The identifier of the entity being proxied.
77 * @param session The session owning the proxy.
79 protected AbstractLazyInitializer(String entityName
, Serializable id
, SessionImplementor session
) {
80 this.entityName
= entityName
;
82 // initialize other fields depending on session state
83 if ( session
== null ) {
87 setSession( session
);
92 public final String
getEntityName() {
97 public final Serializable
getIdentifier() {
102 public final void setIdentifier(Serializable id
) {
107 public final boolean isUninitialized() {
112 public final SessionImplementor
getSession() {
117 public final void setSession(SessionImplementor s
) throws HibernateException
{
118 if ( s
!= session
) {
119 // check for s == null first, since it is least expensive
123 else if ( isConnectedToSession() ) {
124 //TODO: perhaps this should be some other RuntimeException...
125 throw new HibernateException( "illegally attempted to associate a proxy with two open Sessions" );
130 if ( readOnlyBeforeAttachedToSession
== null ) {
131 // use the default read-only/modifiable setting
132 final EntityPersister persister
= s
.getFactory().getEntityPersister( entityName
);
133 setReadOnly( s
.getPersistenceContext().isDefaultReadOnly() || !persister
.isMutable() );
136 // use the read-only/modifiable setting indicated during deserialization
137 setReadOnly( readOnlyBeforeAttachedToSession
.booleanValue() );
138 readOnlyBeforeAttachedToSession
= null;
144 private static EntityKey
generateEntityKeyOrNull(Serializable id
, SessionImplementor s
, String entityName
) {
145 if ( id
== null || s
== null || entityName
== null ) {
148 return s
.generateEntityKey( id
, s
.getFactory().getEntityPersister( entityName
) );
152 public final void unsetSession() {
153 prepareForPossibleSpecialSpecjInitialization();
156 readOnlyBeforeAttachedToSession
= null;
160 public final void initialize() throws HibernateException
{
161 if ( !initialized
) {
162 if ( specjLazyLoad
) {
163 specialSpecjInitialization();
165 else if ( session
== null ) {
166 throw new LazyInitializationException( "could not initialize proxy - no Session" );
168 else if ( !session
.isOpen() ) {
169 throw new LazyInitializationException( "could not initialize proxy - the owning Session was closed" );
171 else if ( !session
.isConnected() ) {
172 throw new LazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
175 target
= session
.immediateLoad( entityName
, id
);
185 protected void specialSpecjInitialization() {
186 if ( session
== null ) {
187 //we have a detached collection thats set to null, reattach
188 if ( sessionFactoryUuid
== null ) {
189 throw new LazyInitializationException( "could not initialize proxy - no Session" );
192 SessionFactoryImplementor sf
= (SessionFactoryImplementor
)
193 SessionFactoryRegistry
.INSTANCE
.getSessionFactory( sessionFactoryUuid
);
194 SessionImplementor session
= (SessionImplementor
) sf
.openSession();
196 // TODO: On the next major release, add an
197 // 'isJTA' or 'getTransactionFactory' method to Session.
198 boolean isJTA
= session
.getTransactionCoordinator()
199 .getTransactionContext().getTransactionEnvironment()
200 .getTransactionFactory()
201 .compatibleWithJtaSynchronization();
204 // Explicitly handle the transactions only if we're not in
205 // a JTA environment. A lazy loading temporary session can
206 // be created even if a current session and transaction are
207 // open (ex: session.clear() was used). We must prevent
208 // multiple transactions.
209 ( ( Session
) session
).beginTransaction();
213 target
= session
.immediateLoad( entityName
, id
);
216 // make sure the just opened temp session gets closed!
219 ( ( Session
) session
).getTransaction().commit();
221 ( (Session
) session
).close();
223 catch (Exception e
) {
224 log
.warn( "Unable to close temporary session used to load lazy proxy associated to no session" );
230 catch (Exception e
) {
232 throw new LazyInitializationException( e
.getMessage() );
235 else if ( session
.isOpen() && session
.isConnected() ) {
236 target
= session
.immediateLoad( entityName
, id
);
241 throw new LazyInitializationException( "could not initialize proxy - Session was closed or disced" );
245 protected void prepareForPossibleSpecialSpecjInitialization() {
246 if ( session
!= null ) {
247 specjLazyLoad
= session
.getFactory().getSettings().isInitializeLazyStateOutsideTransactionsEnabled();
249 if ( specjLazyLoad
&& sessionFactoryUuid
== null ) {
251 sessionFactoryUuid
= (String
) session
.getFactory().getReference().get( "uuid" ).getContent();
253 catch (NamingException e
) {
254 //not much we can do if this fails...
260 private void checkTargetState() {
262 if ( target
== null ) {
263 getSession().getFactory().getEntityNotFoundDelegate().handleEntityNotFound( entityName
, id
);
269 * Getter for property 'connectedToSession'.
271 * @return Value for property 'connectedToSession'.
273 protected final boolean isConnectedToSession() {
274 return getProxyOrNull() != null;
277 private Object
getProxyOrNull() {
278 final EntityKey entityKey
= generateEntityKeyOrNull( getIdentifier(), session
, getEntityName() );
279 if ( entityKey
!= null && session
!= null && session
.isOpen() ) {
280 return session
.getPersistenceContext().getProxy( entityKey
);
286 public final Object
getImplementation() {
292 public final void setImplementation(Object target
) {
293 this.target
= target
;
298 public final Object
getImplementation(SessionImplementor s
) throws HibernateException
{
299 final EntityKey entityKey
= generateEntityKeyOrNull( getIdentifier(), s
, getEntityName() );
300 return (entityKey
== null ?
null : s
.getPersistenceContext().getEntity( entityKey
));
304 * Getter for property 'target'.
306 * Same as {@link #getImplementation()} except that this method will not force initialization.
308 * @return Value for property 'target'.
310 protected final Object
getTarget() {
315 public final boolean isReadOnlySettingAvailable() {
316 return (session
!= null && !session
.isClosed());
319 private void errorIfReadOnlySettingNotAvailable() {
320 if ( session
== null ) {
321 throw new TransientObjectException(
322 "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."
325 if ( session
.isClosed() ) {
326 throw new SessionException(
327 "Session is closed. The read-only/modifiable setting is only accessible when the proxy is associated with an open session."
333 public final boolean isReadOnly() {
334 errorIfReadOnlySettingNotAvailable();
339 public final void setReadOnly(boolean readOnly
) {
340 errorIfReadOnlySettingNotAvailable();
341 // only update if readOnly is different from current setting
342 if ( this.readOnly
!= readOnly
) {
343 final EntityPersister persister
= session
.getFactory().getEntityPersister( entityName
);
344 if ( !persister
.isMutable() && !readOnly
) {
345 throw new IllegalStateException( "cannot make proxies for immutable entities modifiable" );
347 this.readOnly
= readOnly
;
349 EntityKey key
= generateEntityKeyOrNull( getIdentifier(), session
, getEntityName() );
350 if ( key
!= null && session
.getPersistenceContext().containsEntity( key
) ) {
351 session
.getPersistenceContext().setReadOnly( target
, readOnly
);
358 * Get the read-only/modifiable setting that should be put in affect when it is
359 * attached to a session.
361 * This method should only be called during serialization when read-only/modifiable setting
362 * is not available (i.e., isReadOnlySettingAvailable() == false)
364 * @return null, if the default setting should be used;
365 * true, for read-only;
366 * false, for modifiable
368 * @throws IllegalStateException if isReadOnlySettingAvailable() == true
370 protected final Boolean
isReadOnlyBeforeAttachedToSession() {
371 if ( isReadOnlySettingAvailable() ) {
372 throw new IllegalStateException(
373 "Cannot call isReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
376 return readOnlyBeforeAttachedToSession
;
380 * Set the read-only/modifiable setting that should be put in affect when it is
381 * attached to a session.
383 * This method should only be called during deserialization, before associating
384 * the proxy with a session.
386 * @param readOnlyBeforeAttachedToSession, the read-only/modifiable setting to use when
387 * associated with a session; null indicates that the default should be used.
389 * @throws IllegalStateException if isReadOnlySettingAvailable() == true
391 /* package-private */
392 final void setReadOnlyBeforeAttachedToSession(Boolean readOnlyBeforeAttachedToSession
) {
393 if ( isReadOnlySettingAvailable() ) {
394 throw new IllegalStateException(
395 "Cannot call setReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
398 this.readOnlyBeforeAttachedToSession
= readOnlyBeforeAttachedToSession
;
402 public boolean isUnwrap() {
407 public void setUnwrap(boolean unwrap
) {
408 this.unwrap
= unwrap
;