Home > Software design >  How to process Entities into Spring which originate from an external jar file?
How to process Entities into Spring which originate from an external jar file?

Time:10-26

Hello I am have a project with the general following structure:

  1. Core Spring Application, which has an API integrated into it.
  2. Plugins, which are built based on the API.

The Plugins are compiled independently and stored in a folder named "plugins", which is generated in the directory in which the Core Application runs.

The Plugins contain @Entity classes which extend a Super Class from the API.

The Core Spring Application can successfully read and load any classes from the plugins, when loaded independently from Spring. (I have written my own ClassLoader and ClassLoaderManager)

My issue: I have to load the @Entity classes from the Plugins into Spring, so that it recognizes the @Entity classes as "Managed Types".

Failed Solution: I have attempted to remedy this problem by using this Bean:

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean bean = new  LocalContainerEntityManagerFactoryBean();
    bean.setDataSource(dataSource);
    bean.setPackagesToScan(// I inject the packages here);
    bean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    CustomUnitPostProcessor postProcessor = new CustomPostProcessor("base package");
    bean.setPersistenceUnitPostProcessors(postProcessor);
    return bean;
}

public class CustomUnitPostProcessor extends ClasspathScanningPersistenceUnitPostProcessor {

    public CustomUnitPostProcessor(String basePackage) {
        super(basePackage);
    }

    @Override
    public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
        // Adding Jar File Package URLs to PUI via pui.addJarFileURL();
        super.postProcessPersistenceUnitInfo(pui);
    }
}

Unfortunately, this method fails due to the org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [// Class which is supposed to be loaded]. Which breaks the EntityManagerFactory.

I am open to any solutions which would either fix my failed solution, or would achieve the same result.

-AwesomeDude091

CodePudding user response:

The solution was based upon my failed solution and involved injecting a custom Class Loader Service into hibernate. Link for complete answer: How do I inject Hibernate ClassLoaderService into Spring Boot?

  • Related