Hibernate多租户在运行时创建模式

我正在使用hibernate 4和spring 4为java Web应用程序设置多租户支持。在应用程序启动时创建并设置默认架构。 不尝试支持多租户时,此架构工作正常。

我现在需要做的是为每个创建帐户的新租户创建一个架构。 此架构可以只是通用架构的副本,因为它将遵循相同的格式。

如何在运行时创建与默认模式相同格式的新模式? 似乎在实例化LocalSessionFactoryBean时创建了默认模式,因为我指定了映射资源。

我想出了一个解决我问题的解决方案。 我希望对那里的人有用。

因此,主要问题归结为Hibernate在多租户配置期间在运行时为新客户端创建架构的限制。

“Hibernate不支持多租户环境中的自动模式导出。”

我解决这个限制(使用Spring)的解决方案是创建一个新的LocalSessionFactoryBean,配置为不支持多租户。 所以基本上我有两个LocalSessionFactoryBeans。

  1. 多租户LocalSessionFactoryBean,用于多租户会话
  2. 非多租户LocalSessionFactoryBean,用于使用spring文件中的配置集为租户创建架构。

弹簧配置

                                    

用于创建架构的代码

 public boolean createSchema(final String tenantId) throws SQLException { boolean result = false; if(_configuration != null && _dataSource != null) { // Get a local configuration to configure final Configuration tenantConfig = _configuration; // Set the properties for this configuration Properties props = new Properties(); props.put(Environment.DEFAULT_SCHEMA, tenantId); tenantConfig.addProperties(props); // Get connection Connection connection = DriverManager.getConnection(_dataSource.getUrl(), _dataSource.getUsername(), _dataSource.getPassword()); // Create the schema connection.createStatement().execute("CREATE SCHEMA " + tenantId + ""); // Run the schema update from configuration SchemaUpdate schemaUpdate = new SchemaUpdate(tenantConfig); schemaUpdate.execute(true, true); // Set the schema connection.createStatement().execute("SET SCHEMA " + tenantId + ""); // Set the result result = true; } else if(_configuration == null) { if(_LOGGER.isWarnEnabled()) { _LOGGER.warn("No configuration was specified for " + getClass().getSimpleName()); } } else if(_dataSource == null) { if(_LOGGER.isWarnEnabled()) { _LOGGER.warn("No dataSource was specified for " + getClass().getSimpleName()); } } return result; } 

请注意,此代码中的_configuration来自Non Multi-Tenant LocalSessionFactoryBean

你可以使用eclipseLink来解决你的问题。 这里有一些util链接: https : //wiki.eclipse.org/EclipseLink/Examples/JPA/Multitenant和http://www.javacodegeeks.com/2012/02/sneak-peak-at-java-ee-7-multitenant .html或者如果你想使用hibernate,你可以看看这个: http : //docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html/ch16.html和这个关于多租户的例子在hibernate: https : //gist.github.com/dipold/5700724和http://www.devx.com/Java/Article/47817