【问题标题】:Initialize standalone databases, Spring Boot and MyBatis初始化独立数据库、Spring Boot 和 MyBatis
【发布时间】:2017-10-16 15:56:26
【问题描述】:

我正在使用独立的 postgresql 数据库构建 Spring Boot + MyBatis 项目。

嗯,出于某种原因,“基于约定”的数据库初始化不会发生。我手动添加了数据源,创建了 sql 脚本,但是当我运行项目时,从日志中它甚至没有处理这些脚本。我想了解该流程如何用于非嵌入式数据库。

可以使用代码创建数据源的实例吗?

我应该在属性文件或单独的类中链接数据源吗?

如何将单独的数据源(在这种情况下为 postgresql)与 Spring Boot 配置链接?

【问题讨论】:

    标签: spring postgresql spring-boot spring-data mybatis


    【解决方案1】:
    1. 是的

      @Bean
      public DataSource dataSource() {
          DataSourceBuilder.create()
                           .url("jdbc:postgresql://localhost:5432/database")
                           .username("username")
                           .password("password")
                           ...
                           .build();
      }
      

      2-3。您可以使用属性文件以及提供基于 java 的 DataSourceConfiguration

      spring.datasource.url: jdbc:postgresql://localhost:5432/database
      spring.datasource.username: username
      spring.datasource.password: pasword
      

      并在您的配置类中引用这些属性,如下所示:

      @Bean
      @ConfigurationProperties(prefix = "spring.datasource")
      public DataSource dataSource() {
          return DataSourceBuilder.create().build();
      }
      

    如果你只有一个数据库要连接,最方便的方法是将它的连接属性添加到属性文件中,前缀为spring.datasource (scroll here to check available options),并在 pom.xml (build.xml) 中添加org.postgresql 依赖项。 Grade) 文件,其余的由 SpringBoot 完成。

    【讨论】:

    • 感谢您的回复。我正在使用application.properties 文件,与数据源的连接建立良好,但似乎springboot 甚至没有尝试连接。我的意思是,脚本schema.sqldata.sql必须在服务器部署之前执行,我什至不会在日志文件中跟踪它,即使使用spring.jpa.show-sql=true
    • 如果您将spring.jpa.hibernate.ddl-auto 属性设置为create-dropcreate,则这些脚本将被省略。 Schema 是根据您的实体生成的,您可以将初始化 sql 放入类路径根目录下的import.sql 文件中。
    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 2019-11-29
    • 2017-07-29
    • 2022-01-18
    • 2018-03-22
    • 2018-07-25
    • 1970-01-01
    • 2017-09-14
    相关资源
    最近更新 更多