首页 > 解决方案 > 使用 Java 和 Liquibase 在多个模式上应用迁移

问题描述

我正在尝试在我的多租户系统上应用迁移,其中我有一个具有多个架构的数据库,
我这样做是首先获取所有租户然后循环遍历它们并liquibase在更改架构后执行更新,但似乎架构未更改,因为在第一个租户上执行迁移后,第二个租户抛出一个错误,抱怨表已经存在。

    @Override
    @SneakyThrows
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        Connection connection = null;
        Statement statement = null;
        Liquibase liquibase = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            ResultSet result = statement.executeQuery("SELECT nspname FROM pg_namespace WHERE nspname like 'tenant_%'");

            
            List<String> schemas = new ArrayList<>();
            while (result.next()) {
                schemas.add(result.getString(1));
            }
            
            for (String schemaName:schemas) {
                
                connection.setSchema(schemaName);

                Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
                database.setDefaultSchemaName(schemaName);

                log.info("Schema Name: {}",connection.getSchema());

                liquibase = new Liquibase(CHANGE_LOG_FILE, new ClassLoaderResourceAccessor(), database);
                liquibase.update(new Contexts(), new LabelExpression());
            }
        } catch (SQLException | DatabaseException e) {
            e.printStackTrace();
        }finally {
            if(liquibase!=null) {
                liquibase.close();
            }
            if(statement!=null&&!statement.isClosed()) {
                statement.close();
            }
            if(connection!=null&&!connection.isClosed()){
                connection.close();
            }
        }
    }

注意:我在不同的循环中制作它而不使用“try-with-resource”的原因是连接在获取结果集的第一行并更新数据库后关闭,所以我不得不自己关闭它

标签: postgresqlspring-bootliquibasemulti-tenant

解决方案


推荐阅读