[JIRA] (HHH-16845) cached entity with @EmbeddedId cannot use @ElementCollection
by Michael Kroll (JIRA)
Michael Kroll ( https://hibernate.atlassian.net/secure/ViewProfile.jspa?accountId=62ea4af... ) *created* an issue
Hibernate ORM ( https://hibernate.atlassian.net/browse/HHH?atlOrigin=eyJpIjoiMGJlNjY0MDk0... ) / Bug ( https://hibernate.atlassian.net/browse/HHH-16845?atlOrigin=eyJpIjoiMGJlNj... ) HHH-16845 ( https://hibernate.atlassian.net/browse/HHH-16845?atlOrigin=eyJpIjoiMGJlNj... ) cached entity with @EmbeddedId cannot use @ElementCollection ( https://hibernate.atlassian.net/browse/HHH-16845?atlOrigin=eyJpIjoiMGJlNj... )
Issue Type: Bug Assignee: Unassigned Created: 26/Jun/2023 05:02 AM Priority: Major Reporter: Michael Kroll ( https://hibernate.atlassian.net/secure/ViewProfile.jspa?accountId=62ea4af... )
Given a base entity
@Entity(name = "catalog_value" )
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Immutable
public class CatalogValue {
@EmbeddedId
@AttributeOverride(name = "uuid" , column = @Column(name = "id" , updatable = false , nullable = false , columnDefinition = "CHAR(36)" ))
private CatalogValueId id; // don't make final to not break hibernate
@Immutable
@ElementCollection
@CollectionTable(name = "catalog_value_metadata" , joinColumns = {
@JoinColumn(name = "catalog_value_id" , referencedColumnName = "id" ) })
@MapKeyColumn(name = "`key`" )
@AttributeOverride(name = "value.value" , column = @Column(name = "`value`" ))
@AttributeOverride(name = "value.isPublic" , column = @Column(name = "is_public" ))
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
private Map< String , MetadataValue> metadata = new HashMap<>();
[...]
}
this test case
@Test
public void metadataBug() {
final var bav = findByKey("DE-BY"); // has metadata
findByKey("DE"); // has NO metadata
bav.getMetadata().size();
}
leads to
>
>
>
> java.lang.IllegalArgumentException: Can not set java.util.UUID field
> org.example.entity.catalog.CatalogValueId.uuid to
> org.hibernate.engine.spi.CollectionKey
>
>
Reproducer: https://github.com/mickroll/hibernate-test-case-templates/tree/elementcol...
simply build using:
cd orm/hibernate-orm-6
mvn clean install
Full stack trace:
>
>
>
> Tests run: 2, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.331 sec
> <<< FAILURE!
> metadataBug(org.hibernate.bugs.HibernateReproducerTest) Time elapsed:
> 1.258 sec <<< ERROR!
> org.hibernate.property.access.spi.PropertyAccessException: Error accessing
> field [private java.util.UUID
> org.example.entity.catalog.CatalogValueId.uuid] by reflection for
> persistent property org.example.entity.catalog.CatalogValueId#uuid ( #uuid
> ) :
> CollectionKey[org.example.entity.catalog.CatalogValue.metadata#component [uuid]
>
>
> Unknown macro: {uuid=00000001-0000-0001-0000-000000000000}
>
> ]
> at
> org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:50)
>
> at
> org.hibernate.metamodel.mapping.internal.AbstractEmbeddableMapping.getValues(AbstractEmbeddableMapping.java:99)
>
> at
> org.hibernate.type.ComponentType.getPropertyValues(ComponentType.java:447)
>
> at org.hibernate.type.ComponentType.disassemble(ComponentType.java:666)
> at
> org.hibernate.cache.internal.DefaultCacheKeysFactory.staticCreateCollectionKey(DefaultCacheKeysFactory.java:50)
>
> at
> org.hibernate.cache.internal.DefaultCacheKeysFactory.createCollectionKey(DefaultCacheKeysFactory.java:103)
>
> at
> org.hibernate.cache.spi.support.AbstractCollectionDataAccess.generateCacheKey(AbstractCollectionDataAccess.java:38)
>
> at
> org.hibernate.sql.results.internal.ResultsHelper.addCollectionToCache(ResultsHelper.java:285)
>
> at
> org.hibernate.sql.results.internal.ResultsHelper.finalizeCollectionLoading(ResultsHelper.java:203)
>
> at
> org.hibernate.loader.ast.internal.AbstractCollectionBatchLoader.finishInitializingKey(AbstractCollectionBatchLoader.java:86)
>
> at
> org.hibernate.loader.ast.internal.CollectionBatchLoaderArrayParam.loadEmbeddable(CollectionBatchLoaderArrayParam.java:155)
>
> at
> org.hibernate.loader.ast.internal.CollectionBatchLoaderArrayParam.load(CollectionBatchLoaderArrayParam.java:109)
>
> at
> org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:680)
>
> at
> org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:75)
>
> at
> org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:127)
>
> at
> org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1702)
>
> at
> org.hibernate.collection.spi.AbstractPersistentCollection.lambda$initialize$3(AbstractPersistentCollection.java:617)
>
> at
> org.hibernate.collection.spi.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:265)
>
> at
> org.hibernate.collection.spi.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:615)
>
> at
> org.hibernate.collection.spi.AbstractPersistentCollection.read(AbstractPersistentCollection.java:136)
>
> at
> org.hibernate.collection.spi.AbstractPersistentCollection.lambda$readSize$0(AbstractPersistentCollection.java:163)
>
> at
> org.hibernate.collection.spi.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:265)
>
> at
> org.hibernate.collection.spi.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:148)
>
> at org.hibernate.collection.spi.PersistentMap.size(PersistentMap.java:130)
>
> at
> org.hibernate.bugs.HibernateReproducerTest.metadataBug(HibernateReproducerTest.java:34)
>
> at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
> Method)
> at
> java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
>
> at
> java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
>
> at java.base/java.lang.reflect.Method.invoke(Method.java:568)
> at
> org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
>
> at
> org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
>
> at
> org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
>
> at
> org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
>
> at
> org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
>
> at
> org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
>
> at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
> at
> org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
>
> at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
> at
> org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
>
> at
> org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
>
> at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
> at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
> at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
> at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
> at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
> at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
> at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
> at
> org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
>
> at
> org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
>
> at
> org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
>
> at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
> Method)
> at
> java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
>
> at
> java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
>
> at java.base/java.lang.reflect.Method.invoke(Method.java:568)
> at
> org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
>
> at
> org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
>
> at
> org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
>
> at
> org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
>
> at
> org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
> Caused by: java.lang.IllegalArgumentException: Can not set java.util.UUID
> field org.example.entity.catalog.CatalogValueId.uuid to
> org.hibernate.engine.spi.CollectionKey
> at
> java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
>
> at
> java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
>
> at
> java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
>
> at
> java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
>
> at java.base/java.lang.reflect.Field.get(Field.java:425)
> at
> org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:46)
>
> ... 58 more
>
>
>
> Results :
>
>
>
> Tests in error:
> metadataBug(org.hibernate.bugs.HibernateReproducerTest): Error accessing
> field [private java.util.UUID
> org.example.entity.catalog.CatalogValueId.uuid] by reflection for
> persistent property org.example.entity.catalog.CatalogValueId#uuid ( #uuid
> ) :
> CollectionKey[org.example.entity.catalog.CatalogValue.metadata#component [uuid]
>
>
>
>
>
> ]
>
>
( https://hibernate.atlassian.net/browse/HHH-16845#add-comment?atlOrigin=ey... ) Add Comment ( https://hibernate.atlassian.net/browse/HHH-16845#add-comment?atlOrigin=ey... )
Get Jira notifications on your phone! Download the Jira Cloud app for Android ( https://play.google.com/store/apps/details?id=com.atlassian.android.jira.... ) or iOS ( https://itunes.apple.com/app/apple-store/id1006972087?pt=696495&ct=EmailN... ) This message was sent by Atlassian Jira (v1001.0.0-SNAPSHOT#100227- sha1:a102ba3 )
1 year, 6 months
[JIRA] (HHH-16840) Allow serialization of ScanResultImpl to speed up the creation of the entityManagerFactory
by Vincent Bouthinon (JIRA)
Vincent Bouthinon ( https://hibernate.atlassian.net/secure/ViewProfile.jspa?accountId=70121%3... ) *commented* on HHH-16840 ( https://hibernate.atlassian.net/browse/HHH-16840?atlOrigin=eyJpIjoiN2Q5N2... )
Re: Allow serialization of ScanResultImpl to speed up the creation of the entityManagerFactory ( https://hibernate.atlassian.net/browse/HHH-16840?atlOrigin=eyJpIjoiN2Q5N2... )
In my project :
I retrieve the jars and classes directories from the classpath using PersistenceUnitInfo#getJarFileUrls.
public class EfluidPersistenceUnitInfo implements PersistenceUnitInfo {
@Override
public List<URL> getJarFileUrls() {
return ClasspathJarEfluid.getInstance().getURLs();
}
}
package com.efluid.hibernate.core.scanner;
...
/**
* Permet de wrapper {@link ScanResult} avec {@link EfluidScanResult}
* et de récupérer la liste des package -info.java scannés.
*/
public class EfluidScanner extends StandardScanner {
private static final Logger LOG = LoggerFactory.getLogger(EfluidScanner.class);
private static final String FICHIER = "EfluidScanResult.ser" ;
@Override
public ScanResult scan(ScanEnvironment environment, ScanOptions options, ScanParameters parameters) {
long startTime = currentTimeMillis();
ScanResult scan = new EfluidSerialise<ScanResult>().get(FICHIER, ClasspathJarEfluid.getInstance().getChecksum(), () -> super.scan(environment, options, parameters));
LOG.debug( "[TIME] Temps d 'exécution du scan de l' environnement : {} ms" , (currentTimeMillis() - startTime));
return new EfluidScanResult(scan);
}
}
For Serialize :
package com.efluid.hibernate.core.sessionfactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.imrglobal.framework.error.GenericException;
/**
* Permet de récupérer un objet sérialisé ou bien de le sérialiser s 'il n' y est pas déjà.
* Une valeur checksum, permet de savoir si l'objet sérialisé et celui à sérialiser est identique.
* Si ce n 'est pas le cas, alors on écrase l' objet sérialisé par celui à sérialiser.
* Sinon on récupère l'instance désérialiser.
*/
public final class EfluidSerialise<T> {
private static final Logger LOG = LoggerFactory.getLogger(EfluidSerialise.class);
public T get( String nomFichier, long checksum, Supplier<T> supplierObject) {
WrapperObjetSerialise<T> deserialise = deserialise(nomFichier);
if (deserialise == null || deserialise.getChecksum() != checksum) {
LOG.debug( "Sérialisation du fichier {}" , nomFichier);
return serialise(supplierObject.get(), nomFichier, checksum);
}
LOG.debug( "Désérialisation du fichier {}" , nomFichier);
return deserialise.getObjetSerialise();
}
private WrapperObjetSerialise<T> deserialise( String nom) {
if ( new File(nom).exists()) {
try ( var fileInput = new FileInputStream(nom);
var objectInput = new ObjectInputStream(fileInput)) {
return (WrapperObjetSerialise<T>) objectInput.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new GenericException( "Erreur lors de la dé-sérialisation du fichier " + nom, e);
}
}
return null ;
}
private T serialise(T objetASerialise, String nom, long checksum) {
try ( var fout = new FileOutputStream(nom);
var oos = new ObjectOutputStream(fout)) {
oos.writeObject( new WrapperObjetSerialise(objetASerialise, checksum));
} catch (IOException e) {
throw new GenericException( "Erreur lors de la sérialisation du fichier " + nom, e);
}
return objetASerialise;
}
/**
* Permet de stocker la valeur qui permet de déterminer un changement entre l'objet sérialisé et celui à sérialiser.
*/
private static class WrapperObjetSerialise<T> implements Serializable {
private T objetASerialise;
private long checksum;
public WrapperObjetSerialise(T objetASerialise, long checksum) {
this.objetASerialise = objetASerialise;
this.checksum = checksum;
}
public long getChecksum() {
return this.checksum;
}
public T getObjetSerialise() {
return objetASerialise;
}
}
}
package com.efluid.hibernate.core.sessionfactory;
...
/**
* Parcours tous les fichiers d'une arborescence et concatène les dates de modification des fichiers.
* <p>
* Exemple de répertoire scanné : "D:/java/workspaces/developpement_dev/archi/app/target"
*/
public class CheckSumDateModification {
private static final Logger LOG = LoggerFactory.getLogger(CheckSumDateModification.class);
/**
* Parcours la liste des URLs pour calculer le checksum basé sur la date de modification du fichier.
*/
public static long checksum(List<URL> urls) {
return urls.stream().mapToLong(url -> {
try {
return checksum(Paths.get(url.toURI()));
} catch (Throwable e) {
LOG.error( "Erreur lors de la récupération des répertoires classes du classpath." , e);
return 0;
}
}).sum();
}
/**
* Parcours tous les fichiers d'une arborescence et concatène la date de modification des fichiers.
*/
public static long checksum(Path repertoire) {
long start = System.currentTimeMillis();
long check = 0;
try {
check = Files.walk(repertoire)
.filter(Files::isRegularFile)
.mapToLong(getDateModification()).sum();
} catch (IOException e) {
LOG.error( "Erreur lors du calcul de la modification du répertoire : " + repertoire, e);
}
LOG.debug( "Check date modification : {}" , check);
LOG.debug( "Temps d'exécution : {} ms, path {}" , ( System.currentTimeMillis() - start), repertoire);
return check;
}
private static ToLongFunction<Path> getDateModification() {
return file -> {
try {
return Files.readAttributes(file.toAbsolutePath(), BasicFileAttributes.class)
.lastModifiedTime()
.toMillis();
} catch (Throwable e) {
return 0;
}
};
}
}
( https://hibernate.atlassian.net/browse/HHH-16840#add-comment?atlOrigin=ey... ) Add Comment ( https://hibernate.atlassian.net/browse/HHH-16840#add-comment?atlOrigin=ey... )
Get Jira notifications on your phone! Download the Jira Cloud app for Android ( https://play.google.com/store/apps/details?id=com.atlassian.android.jira.... ) or iOS ( https://itunes.apple.com/app/apple-store/id1006972087?pt=696495&ct=EmailN... ) This message was sent by Atlassian Jira (v1001.0.0-SNAPSHOT#100227- sha1:a102ba3 )
1 year, 6 months