在应用运行时通过Spring Boot在需要时创建架构和表

时间:2019-07-09 12:41:33

标签: java postgresql hibernate spring-boot spring-data-jpa

我在启动和运行应用程序时创建新架构存在问题。我设法创建了一个过滤器,该过滤器可在模式之间切换以连接到正确的模式,但现在我想使用Hibernate或Spring在当前应用程序内部创建新的模式。我正在使用MultiTenancyStrategy.SCHEMA方法。

在我的Rest Controller中,我有一种方法是为管理员设计的,可以简单地添加新的应用程序客户/方案。此方法应注意创建架构,表和所有内容。到目前为止,我设法通过启动另一个SpringBoot应用程序作为一个过程来完成所有工作,然后等待它完成。

            try (Statement stmt = dataSource.getConnection().createStatement();) {
                stmt.execute("CREATE SCHEMA "+instance.getDomain()+" AUTHORIZATION "+dbUsername+";");

                //execute java -jar schemacreator ...
                List<String> commands = new ArrayList<>();
                commands.add("java");
                commands.add("-jar");
                commands.add(dbCreatorPath);//database creator path to find an app we have to run
                commands.add(dbUrl);//arg 1 - url for the database
                commands.add(dbUsername);//arg 2 - db username
                commands.add(dbPassword);//arg 3 - db password
                commands.add(instance.getDomain());//arg 4 - name of the generated schema
                Process p = new ProcessBuilder(commands).start();
                if (log.isDebugEnabled()) {
                    try(BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
                        String line;
                        while ((line = input.readLine()) != null) {
                            System.out.println(line);
                        }
                    }
                }
                int exitValue = p.waitFor();
                log.info("Exit value of database creator tool: {}", exitValue);
                if (exitValue!=0) {//tables were created successfully
                    throw new RuntimeException("Exit value of db creator tool was not as expected but was "+exitValue);
                }
            } catch (Exception e) {
                log.error(e.getLocalizedMessage(), e);
            }

这行得通,因为数据库创建者在更新时设置了spring.jpa.hibernate.ddl-auto属性来创建表。也许重要的是要知道我仅使用一个数据源。

那么,是否有任何内部方法/方法可用于在刚刚创建的架构上执行表的创建?最好的办法是,如果可以在classpath上自动找到带注释的类。基本上,与执行ddl的SpringBoot启动相同的过程应该在这里发生。

我正在使用:

spring-boot-starter-parent 2.1.1.RELEASE

spring-boot-starter-data-jpa 2.1.1.RELEASE

PostgreSQL

任何帮助或至少指导都会非常有帮助。谢谢!

0 个答案:

没有答案