我在我的项目中使用 spring + hibernate + oracle。我将 LocalSessionFactoryBean 作为 session 工厂对象,并将不同的 hbm.xml 文件映射到我的项目中。
我的配置如下:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>one.hbm.xml</value>
<value>two.hbm.xml</value>
<value>three.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">....</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.transaction.auto_close_session">true</prop>
<prop key="hibernate.hbm2ddl.auto">none</prop>
</props>
</property>
</bean>
现在我有三个映射文件,每个文件都引用不同的架构。因此,为了映射模式名称,我可以在每个映射文件中提供名称,例如:
<hibernate-mapping schema="one">
但问题是我根据不同的环境有不同的架构名称。那么我如何以编程方式配置它。
最佳答案
我通过在构建映射时修改 spring 配置解决了这个问题。
我通过扩展org.springframework.orm.hibernate4.LocalSessionFactoryBean
创建了一个自定义本地 session 工厂,并添加了以下方法。
protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sessionFactoryBuilder) {
try {
sessionFactoryBuilder.buildMappings();
Iterator<Table> iterator = getConfiguration().getTableMappings();
while (iterator.hasNext()) {
Table table = iterator.next();
if (table.getSchema() != null && !table.getSchema().isEmpty()) {
table.setSchema(mySchemaName);
}
}
} catch (Exception ex) {
logger.error("Exception occurred while building mapping: ", ex);
}
return super.buildSessionFactory(sessionFactoryBuilder);
}
关于java - 使用 spring 在 hibernate 映射文件中动态添加模式名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47902842/