From c18ddc7c15566c0731b2a2155bcfafd6396221e7 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sat, 6 Dec 2025 14:17:00 +0100 Subject: [PATCH] add a cute API to propagate scoped typed objects with the PC --- .../src/main/java/org/hibernate/Session.java | 30 +++++++++++++++++++ .../org/hibernate/internal/SessionImpl.java | 28 +++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/hibernate-core/src/main/java/org/hibernate/Session.java b/hibernate-core/src/main/java/org/hibernate/Session.java index cd4109bc9a24..604800dbc311 100644 --- a/hibernate-core/src/main/java/org/hibernate/Session.java +++ b/hibernate-core/src/main/java/org/hibernate/Session.java @@ -1452,6 +1452,36 @@ public interface Session extends SharedSessionContract, EntityManager { @Override void setProperty(String propertyName, Object value); + /** + * Set a property whose key is the type of the value. + * The value may later be retrieved by calling + * {@link #getProperty(Class)}. If there is already + * a property value of the same type, overwrite it. + * + * @apiNote The application program or framework may + * use this mechanism to register an application or + * framework object whose scope is somehow tied to + * the persistence context. + * + * @param value A non-null Java object + * + * @since 4.0 + */ + @Incubating + void setProperty(Object value); + + /** + * Retrieve a property value set by a previous call to + * {@link #setProperty(Object)}. + * @param type The type of the property value + * @return The property value, or null if no property + * value of the given type was set + * + * @since 4.0 + */ + @Incubating + T getProperty(Class type); + /** * Create a new mutable instance of {@link EntityGraph}, with only * a root node, allowing programmatic definition of the graph from diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java index 82b2f2e250a7..125ca09b1456 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java @@ -2579,6 +2579,34 @@ public LockModeType getLockMode(Object entity) { } + @Override + public void setProperty(Object value) { + if ( value == null ) { + throw new IllegalArgumentException( "Property value may not be null" ); + } + setProperty( value.getClass().getName(), value ); + } + + @Override + public T getProperty(Class type) { + if ( properties == null ) { + return null; + } + else { + final var value = properties.get( type.getName() ); + if ( value == null ) { + return null; + } + else if ( type.isInstance( value ) ) { + // noinspection unchecked + return (T) value; + } + else { + throw new IllegalArgumentException( "Property value is not of expected type: " + type.getName() ); + } + } + } + @Override public void setProperty(String propertyName, Object value) { checkOpen();