2

I have to migrate a hibernate3 spring4 configuration to hibernate5 (or at least 4). So much for the question "Is anybody still using hibernate3?"

The migration involves replacing spring's AnnotationSessionFactoryBean which is not supported for hibernate4/5. I tried to use LocalSessionFactoryBean, but this class does not allow to specify a custom hibernate Configuration object.

The overall goal I try to achieve is to dynamically set the database schema based on the table names. The schema names are not fixed and only resolved at startup time.

Using one sessionFactory to read/write into two separate schemas was implemented to be able to use a single transaction when writing into both schemas. If there a better alternatives to achieve this I'm welcome to other ideas.

Any ideas on how to migrate the following code to hibernate4/5?

@Bean
public AnnotationSessionFactoryBean sessionFactory() throws PropertyVetoException {
    AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean() {
        @Override
        protected org.hibernate.cfg.Configuration newConfiguration() throws HibernateException {
            return new TableSchemaAddingConfig();
        }
    };
    sessionFactory.setDataSource(dataSource);
    ...
    return sessionFactory;
}

class TableSchemaAddingConfig extends org.hibernate.cfg.Configuration {
    @Override
    public Mappings createMappings() {
        return new MappingsImpl() {
            @Override
            public Table addTable(String schema, String catalog, String name, String subselect, boolean isAbstract) {
                schema = getSchema(name);
                return super.addTable(schema, catalog, name, subselect, isAbstract);
            }

            @Override
            public void addTableBinding(String schema, String catalog, String logicalName, String physicalName, Table denormalizedSuperTable) throws DuplicateMappingException {
                schema = getSchema(physicalName);
                super.addTableBinding(schema, catalog, logicalName, physicalName, denormalizedSuperTable);
            }
        };
    }

    private String getSchema(String name) {
        if (StringUtils.startsWithIgnoreCase(name, "FOO_") ||
                StringUtils.startsWithIgnoreCase(name, "BAR_")) {
            return foo_schema; // value based on external configuration settings, not known at compile time
        } else {
            return bar_schema; // value based on external configuration settings, not known at compile time
        }
    }
}
flowerrrr
  • 21
  • 1

0 Answers0