2014-09-03 80 views
1

从hibernate 3版本迁移到4版本期间,我遇到了问题。 我在我的项目中使用spring和hibernate,并且在我的应用程序启动期间,有时我想更改我的实体类的模式。随着3.0版本Hibernate和Spring我通过重写postProcessConfiguration方法LocalSessionFactortBean类是这样做的:在sessionFactory官方化之前更改实体架构名称

@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类,我不知道如何执行此操作。所以可能有人建议我的问题的任何解决方案。

回答

2

查看源代码有助于找到解决方案。 LocalSessionFactoryBean类有方法称为buildSessionFactorynewSessionFactory在以前的版本)。与以前版本的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和创造这一切的班表表示所有类。这之后称为postProcessConfiguration方法。

随着Hibernate 4版我们没有这样的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); 
}