HHH-17172 Retrieve matching session factory either by uuid or name during serialization/deserialization

This commit is contained in:
Marcel Overdijk 2023-09-19 22:39:53 +02:00 committed by Sanne Grinovero
parent 3cb280fa96
commit ab3d4d6d3a
8 changed files with 134 additions and 7 deletions

View File

@ -41,6 +41,7 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
private Boolean readOnlyBeforeAttachedToSession; private Boolean readOnlyBeforeAttachedToSession;
private String sessionFactoryUuid; private String sessionFactoryUuid;
private String sessionFactoryName;
private boolean allowLoadOutsideTransaction; private boolean allowLoadOutsideTransaction;
/** /**
@ -277,6 +278,9 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
// such configuration, so to know if such operation isn't allowed or configured otherwise. // such configuration, so to know if such operation isn't allowed or configured otherwise.
sessionFactoryUuid = session.getFactory().getUuid(); sessionFactoryUuid = session.getFactory().getUuid();
} }
if ( sessionFactoryName == null ) {
sessionFactoryName = session.getFactory().getName();
}
} }
} }
@ -427,6 +431,18 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
return sessionFactoryUuid; return sessionFactoryUuid;
} }
/**
* Get the session factory name.
*
* This method should only be called during serialization,
* and only makes sense after a call to {@link #prepareForPossibleLoadingOutsideTransaction()}.
*
* @return the session factory name.
*/
protected String getSessionFactoryName() {
return sessionFactoryName;
}
/** /**
* Restore settings that are not passed to the constructor, * Restore settings that are not passed to the constructor,
* but are still preserved during serialization. * but are still preserved during serialization.
@ -444,7 +460,7 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
*/ */
/* package-private */ /* package-private */
final void afterDeserialization(Boolean readOnlyBeforeAttachedToSession, final void afterDeserialization(Boolean readOnlyBeforeAttachedToSession,
String sessionFactoryUuid, boolean allowLoadOutsideTransaction) { String sessionFactoryUuid, String sessionFactoryName, boolean allowLoadOutsideTransaction) {
if ( isReadOnlySettingAvailable() ) { if ( isReadOnlySettingAvailable() ) {
throw new IllegalStateException( throw new IllegalStateException(
"Cannot call afterDeserialization when isReadOnlySettingAvailable == true [" + entityName + "#" + id + "]" "Cannot call afterDeserialization when isReadOnlySettingAvailable == true [" + entityName + "#" + id + "]"
@ -453,6 +469,7 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
this.readOnlyBeforeAttachedToSession = readOnlyBeforeAttachedToSession; this.readOnlyBeforeAttachedToSession = readOnlyBeforeAttachedToSession;
this.sessionFactoryUuid = sessionFactoryUuid; this.sessionFactoryUuid = sessionFactoryUuid;
this.sessionFactoryName = sessionFactoryName;
this.allowLoadOutsideTransaction = allowLoadOutsideTransaction; this.allowLoadOutsideTransaction = allowLoadOutsideTransaction;
} }

View File

@ -18,6 +18,7 @@ public abstract class AbstractSerializableProxy implements Serializable {
private final Object id; private final Object id;
private final Boolean readOnly; private final Boolean readOnly;
protected final String sessionFactoryUuid; protected final String sessionFactoryUuid;
protected final String sessionFactoryName;
private final boolean allowLoadOutsideTransaction; private final boolean allowLoadOutsideTransaction;
protected AbstractSerializableProxy( protected AbstractSerializableProxy(
@ -25,11 +26,13 @@ public abstract class AbstractSerializableProxy implements Serializable {
Object id, Object id,
Boolean readOnly, Boolean readOnly,
String sessionFactoryUuid, String sessionFactoryUuid,
String sessionFactoryName,
boolean allowLoadOutsideTransaction) { boolean allowLoadOutsideTransaction) {
this.entityName = entityName; this.entityName = entityName;
this.id = id; this.id = id;
this.readOnly = readOnly; this.readOnly = readOnly;
this.sessionFactoryUuid = sessionFactoryUuid; this.sessionFactoryUuid = sessionFactoryUuid;
this.sessionFactoryName = sessionFactoryName;
this.allowLoadOutsideTransaction = allowLoadOutsideTransaction; this.allowLoadOutsideTransaction = allowLoadOutsideTransaction;
} }
@ -50,6 +53,6 @@ public abstract class AbstractSerializableProxy implements Serializable {
* @param li the {@link AbstractLazyInitializer} to initialize. * @param li the {@link AbstractLazyInitializer} to initialize.
*/ */
protected void afterDeserialization(AbstractLazyInitializer li) { protected void afterDeserialization(AbstractLazyInitializer li) {
li.afterDeserialization( readOnly, sessionFactoryUuid, allowLoadOutsideTransaction ); li.afterDeserialization( readOnly, sessionFactoryUuid, sessionFactoryName, allowLoadOutsideTransaction );
} }
} }

View File

@ -48,4 +48,9 @@ public class MapLazyInitializer extends AbstractLazyInitializer implements Seria
protected String getSessionFactoryUuid() { protected String getSessionFactoryUuid() {
return super.getSessionFactoryUuid(); return super.getSessionFactoryUuid();
} }
@Override
protected String getSessionFactoryName() {
return super.getSessionFactoryName();
}
} }

View File

@ -120,6 +120,7 @@ public class MapProxy implements HibernateProxy, Map, Serializable {
li.getInternalIdentifier(), li.getInternalIdentifier(),
( li.isReadOnlySettingAvailable() ? Boolean.valueOf( li.isReadOnly() ) : li.isReadOnlyBeforeAttachedToSession() ), ( li.isReadOnlySettingAvailable() ? Boolean.valueOf( li.isReadOnly() ) : li.isReadOnlyBeforeAttachedToSession() ),
li.getSessionFactoryUuid(), li.getSessionFactoryUuid(),
li.getSessionFactoryName(),
li.isAllowLoadOutsideTransaction() li.isAllowLoadOutsideTransaction()
); );
} }

View File

@ -15,8 +15,9 @@ public final class SerializableMapProxy extends AbstractSerializableProxy {
Object id, Object id,
Boolean readOnly, Boolean readOnly,
String sessionFactoryUuid, String sessionFactoryUuid,
String sessionFactoryName,
boolean allowLoadOutsideTransaction) { boolean allowLoadOutsideTransaction) {
super( entityName, id, readOnly, sessionFactoryUuid, allowLoadOutsideTransaction ); super( entityName, id, readOnly, sessionFactoryUuid, sessionFactoryName, allowLoadOutsideTransaction );
} }
private Object readResolve() { private Object readResolve() {

View File

@ -87,6 +87,7 @@ public class ByteBuddyInterceptor extends BasicLazyInitializer implements ProxyC
getInternalIdentifier(), getInternalIdentifier(),
( isReadOnlySettingAvailable() ? Boolean.valueOf( isReadOnly() ) : isReadOnlyBeforeAttachedToSession() ), ( isReadOnlySettingAvailable() ? Boolean.valueOf( isReadOnly() ) : isReadOnlyBeforeAttachedToSession() ),
getSessionFactoryUuid(), getSessionFactoryUuid(),
getSessionFactoryName(),
isAllowLoadOutsideTransaction(), isAllowLoadOutsideTransaction(),
getIdentifierMethod, getIdentifierMethod,
setIdentifierMethod, setIdentifierMethod,

View File

@ -37,11 +37,12 @@ public final class SerializableProxy extends AbstractSerializableProxy {
Object id, Object id,
Boolean readOnly, Boolean readOnly,
String sessionFactoryUuid, String sessionFactoryUuid,
String sessionFactoryName,
boolean allowLoadOutsideTransaction, boolean allowLoadOutsideTransaction,
Method getIdentifierMethod, Method getIdentifierMethod,
Method setIdentifierMethod, Method setIdentifierMethod,
CompositeType componentIdType) { CompositeType componentIdType) {
super( entityName, id, readOnly, sessionFactoryUuid, allowLoadOutsideTransaction ); super( entityName, id, readOnly, sessionFactoryUuid, sessionFactoryName, allowLoadOutsideTransaction );
this.persistentClass = persistentClass; this.persistentClass = persistentClass;
this.interfaces = interfaces; this.interfaces = interfaces;
if ( getIdentifierMethod != null ) { if ( getIdentifierMethod != null ) {
@ -110,16 +111,16 @@ public final class SerializableProxy extends AbstractSerializableProxy {
} }
private Object readResolve() { private Object readResolve() {
final SessionFactoryImplementor sessionFactory = retrieveMatchingSessionFactory( this.sessionFactoryUuid ); final SessionFactoryImplementor sessionFactory = retrieveMatchingSessionFactory( this.sessionFactoryUuid, this.sessionFactoryName );
BytecodeProviderImpl byteBuddyBytecodeProvider = retrieveByteBuddyBytecodeProvider( sessionFactory ); BytecodeProviderImpl byteBuddyBytecodeProvider = retrieveByteBuddyBytecodeProvider( sessionFactory );
HibernateProxy proxy = byteBuddyBytecodeProvider.getByteBuddyProxyHelper().deserializeProxy( this ); HibernateProxy proxy = byteBuddyBytecodeProvider.getByteBuddyProxyHelper().deserializeProxy( this );
afterDeserialization( (ByteBuddyInterceptor) proxy.getHibernateLazyInitializer() ); afterDeserialization( (ByteBuddyInterceptor) proxy.getHibernateLazyInitializer() );
return proxy; return proxy;
} }
private static SessionFactoryImplementor retrieveMatchingSessionFactory(final String sessionFactoryUuid) { private static SessionFactoryImplementor retrieveMatchingSessionFactory(final String sessionFactoryUuid, final String sessionFactoryName) {
Objects.requireNonNull( sessionFactoryUuid ); Objects.requireNonNull( sessionFactoryUuid );
final SessionFactoryImplementor sessionFactory = SessionFactoryRegistry.INSTANCE.getSessionFactory( sessionFactoryUuid ); final SessionFactoryImplementor sessionFactory = SessionFactoryRegistry.INSTANCE.findSessionFactory( sessionFactoryUuid, sessionFactoryName );
if ( sessionFactory != null ) { if ( sessionFactory != null ) {
return sessionFactory; return sessionFactory;
} }

View File

@ -0,0 +1,98 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.orm.test.proxy;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.internal.util.SerializationHelper;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
/**
* This integration test verifies that serialized entities
* can be deserialized and re-connected to a SessionFactory
* by using the SessionFactory name rather than its UUID.
* This is relevant for clustering, as different SessionFactory
* instances on different nodes will have a different UUID
* but can be configured to match the name.
*
* @author Marcel Overdijk
*/
public class MultipleSessionFactoriesProxyTest extends BaseCoreFunctionalTestCase {
@Override
public String[] getMappings() {
return new String[] { "proxy/DataPoint.hbm.xml" };
}
@Override
protected String getBaseForMappings() {
return "org/hibernate/orm/test/";
}
@Override
public void configure(Configuration cfg) {
super.configure( cfg );
cfg.setProperty( Environment.SESSION_FACTORY_NAME, "sf-name" ); // explicitly define the session factory name
cfg.setProperty( Environment.SESSION_FACTORY_NAME_IS_JNDI, "false" ); // do not bind it to jndi
}
@Test
@TestForIssue(jiraKey = "HHH-17172")
public void testProxySerializationWithMultipleSessionFactories() {
Session s = openSession();
Transaction t = s.beginTransaction();
Container container = new Container( "container" );
container.setOwner( new Owner( "owner" ) );
container.setInfo( new Info( "blah blah blah" ) );
container.getDataPoints().add( new DataPoint( new BigDecimal( 1 ), new BigDecimal( 1 ), "first data point" ) );
container.getDataPoints().add( new DataPoint( new BigDecimal( 2 ), new BigDecimal( 2 ), "second data point" ) );
s.persist( container );
s.flush();
s.clear();
container = s.load( Container.class, container.getId() );
assertFalse( Hibernate.isInitialized( container ) );
container.getId();
assertFalse( Hibernate.isInitialized( container ) );
container.getName();
assertTrue( Hibernate.isInitialized( container ) );
t.commit();
s.close();
// Serialize the container.
byte[] bytes = SerializationHelper.serialize( container );
// Now deserialize, which works at this stage, because the session factory UUID in the
// serialized object is the same as the current session factory.
SerializationHelper.deserialize( bytes );
// Now rebuild the session factory (it will get a new unique UUID).
// As configured for this test an explicit session factory name is used ("sf-name"),
// so we would expect the deserialization to work after rebuilding the session factory.
// Rebuilding the session factory simulates multiple JVM instances with different session
// factories (different UUID's, but same name!) trying to deserialize objects from a
// centralized cache (e.g. Hazelcast).
rebuildSessionFactory();
// And this should be possible now: even though we lack of a matching session factory by
// UUID, it should seek a match by using the session factory name as valid alternative.
SerializationHelper.deserialize( bytes );
}
}