Spring Boot / JPA / Hibernate,如何根据 Spring 配置文件切换数据库供应商?

Spring Boot / JPA / Hibernate, How to switch database vendor according to Spring profile?

我正在使用 Spring Boot/JPA/Hibernate。我想在本地主机上测试时使用 HSQLDB,在服务器上部署时 MySQL。

在 pom.xml 中,我对 MySQL 有这样的依赖:

 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
 </dependency>

HSQLDB 的依赖关系:

<dependency>
   <groupId>org.hsqldb</groupId>
   <artifactId>hsqldb</artifactId>
</dependency>

由于 Spring 引导自动配置,我可能无法将两个依赖项都放在 pom.xml 中。但是我想在 local Spring 配置文件处于活动状态时使用 HSQLDB,而在 server Spring 配置文件处于活动状态时使用 MySQL。理想情况下,我只想生成一个 war 文件和 运行 带有 mvn spring-boot:run 的本地版本,并从 war 文件部署服务器版本。

有什么想法吗?

P.S.: 我正在使用 maven

您需要创建 Maven 配置文件 而不是 spring 配置文件并相应地添加依赖项。创建一个具有 hsqldb 依赖关系的 local 配置文件,并在开发模式下激活它。然后创建一个具有 mysql 依赖关系的 server 配置文件,并在打包部署到服务器时激活它。我个人更喜欢 devrelease 作为命名约定(但这是我的拙见)。然后你必须使用 spring profile

快捷方式 maven profile
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>xyz</version>
    <configuration>
      <profiles>
        <profile>local</profile>....

在本地个人资料中并且

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>1.4.1.RELEASE</version>
    <configuration>
      <profiles>
        <profile>server</profile>...

在服务器配置文件和 运行 使用此开关的所需配置

mvn spring-boot:run -P[local or server]

Introduction to Build Profiles

I probably can't put both dependencies in pom.xml due to Spring Boot autoconfiguration.

当然你可以同时拥有它们。有几种解决方案。

最基本的方法是同时拥有两个依赖项,并使用 mysql 数据库的设置在您的项目中创建一个 application-server.properties。当您 运行 没有特定配置文件的应用程序时,Spring 启动将找不到任何连接到 MySQL 的信息,因此它将回退到 HSQL。在服务器上部署应用程序时,请确保启用 server 配置文件。相同的工件可用于两种用例。

您可以通过在生成 fat jar 时排除 hsql 依赖项来稍微改进该解决方案。这样做的好处是,如果您忘记启用配置文件,您将在启动时遇到异常,而不是默默地使用内存中的数据库。要排除 hsql,只需 configure the maven plugin。您将能够在本地 (mvn spring-boot:run) 或您的 IDE 中安装 运行 应用程序,并且 fat jar 将仅包含 mysql 依赖项。不过,您仍然需要启用 server 配置文件。

如果您使用的是 war,则不能使用最后一个解决方案:切换到 jar 的另一个原因 ;-)