Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HHH-18976 Avoid usage of Array.newInstance #9589

Merged
merged 6 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.build.AllowReflection;
import org.hibernate.metamodel.mapping.PluralAttributeMapping;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.type.Type;
Expand All @@ -34,6 +35,7 @@
* @author Gavin King
*/
@Incubating
@AllowReflection // We need the ability to create arrays of the same type as in the model.
public class PersistentArrayHolder<E> extends AbstractPersistentCollection<E> {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( PersistentArrayHolder.class );

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.Objects;

import org.hibernate.Internal;
import org.hibernate.internal.build.AllowReflection;
import org.hibernate.internal.util.CharSequenceHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.metamodel.mapping.EmbeddableMappingType;
Expand Down Expand Up @@ -1612,6 +1613,7 @@ public Object[] toArray() {
}

@Override
@AllowReflection // We need the ability to create arrays of requested types dynamically.
public <T> T[] toArray(T[] a) {
//noinspection unchecked
final T[] r = a.length >= size
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.Size;
import org.hibernate.internal.build.AllowReflection;
import org.hibernate.metamodel.mapping.JdbcMappingContainer;
import org.hibernate.metamodel.mapping.SqlTypedMapping;
import org.hibernate.metamodel.model.domain.DomainType;
Expand All @@ -24,6 +25,7 @@

public class DdlTypeHelper {
@SuppressWarnings("unchecked")
@AllowReflection
public static BasicType<?> resolveArrayType(DomainType<?> elementType, TypeConfiguration typeConfiguration) {
@SuppressWarnings("unchecked") final BasicPluralJavaType<Object> arrayJavaType = (BasicPluralJavaType<Object>) typeConfiguration.getJavaTypeRegistry()
.getDescriptor(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.util.List;
import java.util.function.Supplier;

import org.hibernate.internal.build.AllowReflection;
import org.hibernate.metamodel.mapping.BasicValuedMapping;
import org.hibernate.metamodel.mapping.MappingModelExpressible;
import org.hibernate.metamodel.model.domain.DomainType;
Expand Down Expand Up @@ -78,6 +79,7 @@ public BasicValuedMapping resolveFunctionReturnType(
return null;
}

@AllowReflection
public static <T> BasicType<?> resolveJsonArrayType(DomainType<T> elementType, TypeConfiguration typeConfiguration) {
final Class<?> arrayClass = Array.newInstance( elementType.getBindableJavaType(), 0 ).getClass();
@SuppressWarnings("unchecked")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.hibernate.event.service.spi.EventListenerRegistrationException;
import org.hibernate.event.service.spi.JpaBootstrapSensitive;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.build.AllowReflection;
import org.hibernate.jpa.event.spi.CallbackRegistry;
import org.hibernate.jpa.event.spi.CallbackRegistryConsumer;

Expand Down Expand Up @@ -350,6 +351,7 @@ private void handleListenerAddition(T listener, Consumer<T> additionHandler) {
}

@SuppressWarnings("unchecked")
@AllowReflection // Possible array types are registered in org.hibernate.graalvm.internal.StaticClassLists.typesNeedingArrayCopy
private T[] createListenerArrayForWrite(int len) {
return (T[]) Array.newInstance( eventType.baseListenerInterface(), len );
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import org.hibernate.event.service.spi.EventListenerRegistrationException;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.build.AllowReflection;
import org.hibernate.jpa.event.spi.CallbackRegistry;

import static org.hibernate.event.spi.EventType.AUTO_FLUSH;
Expand Down Expand Up @@ -122,6 +123,7 @@ public final <T> void setListeners(EventType<T> type, Class<? extends T>... list
}

@SafeVarargs
@AllowReflection // Possible array types are registered in org.hibernate.graalvm.internal.StaticClassLists.typesNeedingArrayCopy
private <T> T[] resolveListenerInstances(EventType<T> type, Class<? extends T>... listenerClasses) {
@SuppressWarnings("unchecked")
T[] listeners = (T[]) Array.newInstance( type.baseListenerInterface(), listenerClasses.length );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import org.hibernate.graph.GraphSemantic;
import org.hibernate.graph.RootGraph;
import org.hibernate.graph.spi.RootGraphImplementor;
import org.hibernate.loader.ast.internal.LoaderHelper;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.loader.ast.spi.MultiIdLoadOptions;

Expand Down Expand Up @@ -191,7 +190,7 @@ public <K> List<T> multiLoad(List<K> ids) {
}
else {
return perform( () -> (List<T>) entityPersister.multiLoad(
ids.toArray( LoaderHelper.createTypedArray( ids.get( 0 ).getClass(), ids.size() ) ),
ids.toArray( new Object[0] ),
Comment on lines -194 to +193
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note this is still done, but deeper within the multiLoad call, and only when necessary (see MultiIdEntityLoaderArrayParam).

session,
this
) );
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* SPDX-License-Identifier: LGPL-2.1-or-later
* Copyright Red Hat Inc. and Hibernate Authors
*/
package org.hibernate.internal.build;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;

@Retention( RetentionPolicy.CLASS )
@Target({ TYPE, METHOD, CONSTRUCTOR })
public @interface AllowReflection {
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.internal.build.AllowReflection;
import org.hibernate.type.Type;

public final class ArrayHelper {
Expand Down Expand Up @@ -59,6 +60,7 @@ public static int indexOf(Object[] array, int end, Object object) {
}

@SuppressWarnings("unchecked")
@AllowReflection
public static <T> T[] filledArray(T value, Class<T> valueJavaType, int size) {
final T[] array = (T[]) Array.newInstance( valueJavaType, size );
Arrays.fill( array, value );
Expand Down Expand Up @@ -202,6 +204,7 @@ public static int[] join(int[] x, int[] y) {
}

@SuppressWarnings("unchecked")
@AllowReflection
public static <T> T[] join(T[] x, T... y) {
T[] result = (T[]) Array.newInstance( x.getClass().getComponentType(), x.length + y.length );
System.arraycopy( x, 0, result, 0, x.length );
Expand Down Expand Up @@ -519,7 +522,12 @@ public static <T> void forEach(T[] array, Consumer<T> consumer) {
}
}

/**
* @deprecated Use {@link Array#newInstance(Class, int)} instead.
*/
@Deprecated
@SuppressWarnings("unchecked")
@AllowReflection
public static <T> T[] newInstance(Class<T> elementType, int length) {
return (T[]) Array.newInstance( elementType, length );
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import jakarta.persistence.PersistenceException;

import org.hibernate.internal.build.AllowReflection;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.internal.util.collections.MapBackedClassValue;
import org.hibernate.internal.util.collections.ReadOnlyMap;
Expand Down Expand Up @@ -168,6 +169,7 @@ public static class Builder {
private final Map<Class<?>, Callback[]> postUpdates = new HashMap<>();
private final Map<Class<?>, Callback[]> postLoads = new HashMap<>();

@AllowReflection
public void registerCallbacks(Class<?> entityClass, Callback[] callbacks) {
if ( callbacks != null ) {
for ( Callback callback : callbacks ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.build.AllowReflection;
import org.hibernate.loader.ast.spi.CollectionBatchLoader;
import org.hibernate.metamodel.mapping.NonAggregatedIdentifierMapping;
import org.hibernate.metamodel.mapping.PluralAttributeMapping;
Expand Down Expand Up @@ -126,6 +127,7 @@ protected void finishInitializingKey(Object key, SharedSessionContractImplemento

}

@AllowReflection
Object[] resolveKeysToInitialize(Object keyBeingLoaded, SharedSessionContractImplementor session) {
final int length = getDomainBatchSize();
final Object[] keysToInitialize = (Object[]) Array.newInstance(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import org.hibernate.sql.exec.spi.JdbcSelectExecutor;
import org.hibernate.type.descriptor.java.JavaType;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

Expand All @@ -39,14 +38,12 @@
public abstract class AbstractMultiIdEntityLoader<T> implements MultiIdEntityLoader<T> {
private final EntityMappingType entityDescriptor;
private final SessionFactoryImplementor sessionFactory;
private final EntityIdentifierMapping identifierMapping;
protected final Object[] idArray;
protected final EntityIdentifierMapping identifierMapping;

public AbstractMultiIdEntityLoader(EntityMappingType entityDescriptor, SessionFactoryImplementor sessionFactory) {
this.entityDescriptor = entityDescriptor;
this.sessionFactory = sessionFactory;
identifierMapping = getLoadable().getIdentifierMapping();
idArray = (Object[]) Array.newInstance( identifierMapping.getJavaType().getJavaTypeClass(), 0 );
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was the main problem affecting Quarkus, FWIW.
This being done in the abstract class meant it was done for MultiIdEntityLoaderArrayParam -- where it's needed, and generally innocuous since it handles things like Integer[] -- but also MultiIdEntityLoaderStandardParam -- where it's not needed, and possibly problematic as it could be handling things like MyIdClass[], requiring MyIdClass[] (the array type) to be registered for reflection in native images.
It's not trivial to detect all ID types in Quarkus (think of orm.xml using property access, or IDs defined in mappedsuperclasses with generics), so this need for registering MyIdClass[] for reflection was a problem.

}

protected EntityMappingType getEntityDescriptor() {
Expand Down Expand Up @@ -301,10 +298,13 @@ else if ( unresolvedIds.size() == ids.length ) {
}
else {
// we need to load only some the ids
return unresolvedIds.toArray( idArray );
return toIdArray( unresolvedIds );
}
}

// Depending on the implementation, a specific subtype of Object[] (e.g. Integer[]) may be needed.
protected abstract Object[] toIdArray(List<Object> ids);

private boolean isIdCoercionEnabled() {
return !getSessionFactory().getJpaMetamodel().getJpaCompliance().isLoadByIdComplianceEnabled();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.engine.spi.SubselectFetch;
import org.hibernate.internal.build.AllowReflection;
import org.hibernate.loader.ast.spi.CollectionBatchLoader;
import org.hibernate.loader.ast.spi.SqlArrayMultiKeyLoader;
import org.hibernate.metamodel.mapping.ForeignKeyDescriptor;
Expand All @@ -31,7 +32,6 @@
import org.hibernate.sql.exec.spi.JdbcParametersList;
import org.hibernate.sql.results.internal.RowTransformerStandardImpl;
import org.hibernate.sql.results.spi.ListResultsConsumer;
import org.hibernate.type.BasicType;

import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.hasSingleId;
import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.trimIdBatch;
Expand Down Expand Up @@ -68,17 +68,12 @@ public CollectionBatchLoaderArrayParam(

final ForeignKeyDescriptor keyDescriptor = getLoadable().getKeyDescriptor();
final JdbcMapping jdbcMapping = keyDescriptor.getSingleJdbcMapping();
final Class<?> jdbcArrayClass = Array.newInstance( jdbcMapping.getJdbcJavaType().getJavaTypeClass(), 0 )
.getClass();
final Class<?> jdbcJavaTypeClass = jdbcMapping.getJdbcJavaType().getJavaTypeClass();
keyDomainType = getKeyType( keyDescriptor.getKeyPart() );

final BasicType<?> arrayBasicType = getSessionFactory().getTypeConfiguration()
.getBasicTypeRegistry()
.getRegisteredType( jdbcArrayClass );
arrayJdbcMapping = MultiKeyLoadHelper.resolveArrayJdbcMapping(
arrayBasicType,
jdbcMapping,
jdbcArrayClass,
jdbcJavaTypeClass,
getSessionFactory()
);

Expand Down Expand Up @@ -115,6 +110,7 @@ public PersistentCollection<?> load(Object keyBeingLoaded, SharedSessionContract

}

@AllowReflection
private PersistentCollection<?> loadEmbeddable(
Object keyBeingLoaded,
SharedSessionContractImplementor session,
Expand Down Expand Up @@ -216,6 +212,7 @@ void finishInitializingKeys(Object[] keys, SharedSessionContractImplementor sess
}

@Override
@AllowReflection
Object[] resolveKeysToInitialize(Object keyBeingLoaded, SharedSessionContractImplementor session) {
final ForeignKeyDescriptor keyDescriptor = getLoadable().getKeyDescriptor();
if( keyDescriptor.isEmbedded()){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.hibernate.LockOptions;
import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.build.AllowReflection;
import org.hibernate.loader.ast.spi.SqlArrayMultiKeyLoader;
import org.hibernate.metamodel.mapping.BasicEntityIdentifierMapping;
import org.hibernate.metamodel.mapping.EntityIdentifierMapping;
Expand Down Expand Up @@ -75,12 +76,10 @@ public EntityBatchLoaderArrayParam(
}

identifierMapping = (BasicEntityIdentifierMapping) getLoadable().getIdentifierMapping();
final Class<?> arrayClass =
Array.newInstance( identifierMapping.getJavaType().getJavaTypeClass(), 0 ).getClass();
final Class<?> idClass = identifierMapping.getJavaType().getJavaTypeClass();
arrayJdbcMapping = MultiKeyLoadHelper.resolveArrayJdbcMapping(
sessionFactory.getTypeConfiguration().getBasicTypeRegistry().getRegisteredType( arrayClass ),
identifierMapping.getJdbcMapping(),
arrayClass,
idClass,
sessionFactory
);

Expand All @@ -106,6 +105,7 @@ public int getDomainBatchSize() {
return domainBatchSize;
}

@AllowReflection
protected Object[] resolveIdsToInitialize(Object pkValue, SharedSessionContractImplementor session) {
//TODO: should this really be different to EntityBatchLoaderInPredicate impl?
final Class<?> idType = identifierMapping.getJavaType().getJavaTypeClass();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.hibernate.event.monitor.spi.EventMonitor;
import org.hibernate.event.spi.EventSource;
import org.hibernate.event.monitor.spi.DiagnosticEvent;
import org.hibernate.internal.build.AllowReflection;
import org.hibernate.loader.LoaderLogging;
import org.hibernate.metamodel.mapping.BasicValuedModelPart;
import org.hibernate.metamodel.mapping.EntityMappingType;
Expand Down Expand Up @@ -202,6 +203,7 @@ public static <K> K[] normalizeKeys(
* @param elementClass The type of the array elements. See {@link Class#getComponentType()}
* @param length The length to which the array should be created. This is usually zero for Hibernate uses
*/
@AllowReflection
public static <X> X[] createTypedArray(Class<X> elementClass, @SuppressWarnings("SameParameterValue") int length) {
//noinspection unchecked
return (X[]) Array.newInstance( elementClass, length );
Expand Down
Loading
Loading