0

I migrate from Hibernate 5.0 to 5.2 and currently facing a problem with load mappings from other jars. I would like to make a code absolutely free of XML, so, need to configure Hibernate programmatically. Here is my HibernateConfiguration:

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:core.properties" })
@ComponentScan({ "com.test.core.domain" })
public class HibernateConfiguration {
    private static Logger logger = Logger.getLogger(HibernateConfiguration.class);
    private final static String HIBERNATE_DIALECT = "org.hibernate.dialect.PostgreSQL95Dialect";

    @Autowired private Environment env;
    @Autowired private ResourceLoader resourceLoader;

    @Bean
    public SessionFactory sessionFactory() throws IOException {
        StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();
        standardServiceRegistryBuilder.applySettings(additionalProperties());
        standardServiceRegistryBuilder.applySetting("hibernate.connection.datasource",dataSource());

        MetadataSources metadataSources = new MetadataSources(standardServiceRegistryBuilder.build());

        Resource resource = resourceLoader.getResource("classpath*:/hibernate");
        File file = resource.getFile();
        Iterator<File> fi = FileUtils.iterateFiles(file, null, true);
        while(fi.hasNext()) {
            metadataSources.addFile(fi.next());
            logger.info("URL to hibernate is: " + fi.next());
        }
        Metadata metadata = metadataSources.getMetadataBuilder().build();
        return metadata.getSessionFactoryBuilder().build();
    }

    @Bean
    public DataSource dataSource() {
        ComboPooledDataSource сomboPooledDataSource = new ComboPooledDataSource();
        try {
            сomboPooledDataSource.setDriverClass(Preconditions.checkNotNull(env.getProperty("jdbc.driver-class-name")));
        } catch( PropertyVetoException pve ){
            logger.error("Cannot load datasource driver (" + env.getProperty("jdbc.driver-class-name") +"): " + pve.getMessage());
            return null;
        }

        сomboPooledDataSource.setJdbcUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
        сomboPooledDataSource.setUser(Preconditions.checkNotNull(env.getProperty("jdbc.username")));
        сomboPooledDataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.password")));

        сomboPooledDataSource.setMinPoolSize(20);
        сomboPooledDataSource.setMaxPoolSize(50);
        сomboPooledDataSource.setCheckoutTimeout(15);
        сomboPooledDataSource.setMaxStatements(0);
        сomboPooledDataSource.setIdleConnectionTestPeriod(30);

        return сomboPooledDataSource;
    }

    @Bean
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) throws Exception{
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory());
        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();
    }

    private static Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", HIBERNATE_DIALECT);
        properties.setProperty("hibernate.bytecode.use_reflection_optimizer", "true");
        properties.setProperty("hibernate.show_sql", "false");
        properties.setProperty("hibernate.hbm2ddl.auto", "validate");
        properties.setProperty("hibernate.default_batch_fetch_size", "1000");
        properties.setProperty("hibernate.max_fetch_depth", "2");
        properties.setProperty("hibernate.generate_statistics", "false");
        properties.setProperty("hibernate.default_schema", "EDRIVE");

        properties.setProperty("hibernate.connection.CharSet", "utf8");
        properties.setProperty("hibernate.connection.characterEncoding", "utf8");
        properties.setProperty("hibernate.connection.useUnicode", "true");
        properties.setProperty("hibernate.connection.release_mode", "after_transaction");

        properties.setProperty("hibernate.jdbc.batch_size", "50");
        properties.setProperty("hibernate.jdbc.fetch_size", "500");
        properties.setProperty("hibernate.jdbc.use_scrollable_resultset", "false");

        properties.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory");
        properties.setProperty("hibernate.cache.use_query_cache", "true");
        properties.setProperty("hibernate.cache.use_second_level_cache", "true");
        properties.setProperty("hibernate.cache.use_structured_entries", "false");

        properties.setProperty("hibernate.current.session.context.class", "org.springframework.orm.hibernate5.SpringSessionContext");

        return properties;
    }
}

Current implementation throws FileNotFoundException:

java.io.FileNotFoundException: ServletContext resource [/classpath*:/hibernate] cannot be resolved to absolute file path - web application archive not expanded?

So, the question is - how to add my mappings *.hbm.xml stored in other jar?

Green Root
  • 644
  • 2
  • 10
  • 28
  • It's a `Resource` not a `File`. Avoid attempting to convert opaque resource locations into `File` instances - the resources are located on the classpath, these can in theory be _anywhere_. What are these files for anyway? I thought you were XML free - [for example](https://spring.io/guides/gs/accessing-data-jpa/)? – Boris the Spider Apr 01 '18 at 13:34
  • [Might be worth a read](https://stackoverflow.com/a/36912783/2071828) - you seem to be reinventing quite a number of wheels... – Boris the Spider Apr 01 '18 at 13:49
  • It also does not work - as far as I understand, Hibernate 5.2 requires to have Metadata defined. I get following exception during startup: java.lang.NullPointerException at org.hibernate.metamodel.internal.AttributeFactory.getMetaModelType(AttributeFactory.java:202) – Green Root Apr 01 '18 at 19:14

0 Answers0