在sessionFactory初始化之前更改实体架构名称



在从hibernate 3版本迁移到4版本的过程中,我遇到了问题。我在项目中使用spring和hibernate,在应用程序启动期间,有时我想更改实体类的模式。对于hibernate和spring的3个版本,我通过覆盖LocalSessionFactortBean类中的postProcessConfiguration方法来实现这一点,如下所示:

@SuppressWarnings("unchecked")
    @Override
    protected void postProcessAnnotationConfiguration(AnnotationConfiguration config)
    {
        Iterator<Table> it = config.getTableMappings();
        while (it.hasNext())
        {
            Table table = it.next();
            table.setSchema(schemaConfigurator.getSchemaName(table.getSchema()));
        }
    }

这对我来说是完美的。但在hibernate4.LocalSessionFactoryBean类中,所有的后处理方法都被删除了。有些人建议使用ServiceRegistryBuilder类,但我想为我的会话工厂使用spring-xml配置,而对于ServiceRegistryBuilder类,我不知道如何执行此操作。所以,也许有人会为我的问题提出任何解决方案。

查看源代码有助于找到解决方案。LocalSessionFactoryBean类具有名为buildSessionFactory的方法(以前版本中为newSessionFactory)。对于以前版本的Hibernate(3版本),在该方法调用之前处理了一些操作。你可以在官方文档中看到它们

        // Tell Hibernate to eagerly compile the mappings that we registered,
        // for availability of the mapping information in further processing.
        postProcessMappings(config);
        config.buildMappings();

正如我所理解的(可能我错了),这个buildMapping方法解析指定为映射类或放置在packagesToScan中的所有类,并创建所有这些类的表表示。此后称为CCD_ 9方法。

对于Hibernate4版本,我们没有这样的postProcess方法。但我们可以像这样覆盖buildSessionFactory方法:

@Override
protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb) {
    sfb.buildMappings();
    // For my task we need this
    Iterator<Table> iterator = getConfiguration().getTableMappings();
    while (iterator.hasNext()){
        Table table = iterator.next();
        if(table.getSchema() != null && !table.getSchema().isEmpty()){
            table.setSchema(schemaConfigurator.getSchemaName(table.getSchema()));
        }
    }
    return super.buildSessionFactory(sfb);
}

最新更新