【问题标题】:Spring Boot: Setting Hibernate naming strategy with @DataJpaTest and FlywaySpring Boot:使用 @DataJpaTest 和 Flyway 设置 Hibernate 命名策略
【发布时间】:2019-07-05 08:25:43
【问题描述】:

当我尝试在也使用 Flyway 的 Spring Boot 测试中使用 @DataJpaTest 注释时,我注意到了一个奇怪的行为。

给定以下实体类:

@Entity
public class MyEntity {

  @Id
  private String columnA;
  private String columnB;

  public String getColumnA() {
      return columnA;
  }

  public void setColumnA(String columnA) {
      this.columnA = columnA;
  }

  public String getColumnB() {
      return columnB;
  }

  public void setColumnB(String columnB) {
      this.columnB = columnB;
  }
}

以下 Spring 存储库:

@Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, String> {
}

以下测试:

@RunWith(SpringRunner.class)
@DataJpaTest
public class JpaTestApplicationTests {

  @Autowired
  MyEntityRepository myEntityRepository;

  @Test
  public void canSaveAndFetch() {
      MyEntity myEntity = new MyEntity();
      myEntity.setColumnA("a");
      myEntity.setColumnB("b");

      myEntityRepository.save(myEntity);
      Optional<MyEntity> myEntityOptional = myEntityRepository.findById("a");
      Assert.assertTrue(myEntityOptional.isPresent());
  }
}

测试本身运行良好,因为 auto-ddl 已打开且 H2 正在创建表。

但是,如果我想定义自己的架构,那么我将 Flyway 添加到 POM 并创建迁移,例如在资源/db/migration/V1__Schema.sql:

CREATE TABLE my_entity (
  column_a VARCHAR NOT NULL PRIMARY KEY,
  column_b VARCHAR
);

现在相同的测试将失败,因为 JPA 不再使用默认的 SpringPhysicalNamingStrategy。

原因:org.h2.jdbc.JdbcSQLException:找不到列“MYENTITY0_.COLUMNA”

通过设置这似乎是一个简单的修复

spring.jpa.hibernate.naming.physical-strategy = org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

但是,无论我把它放在 application.properties 中,还是放在 @TestPropertySource 中,或者创建一个 PhysicalNamingStrategy bean... 都不会影响行为。如何在此测试上下文中告诉 JPA 我想使用将“columnA”映射到“column_a”的 SpringPhysicalNamingStrategy?

【问题讨论】:

  • 你解决过这个问题吗?

标签: spring-boot jpa junit h2 flyway


【解决方案1】:

我遇到了类似的问题 - 此属性 (spring.jpa.hibernate.naming.physical-strategy) 被忽略(与其他 spring.jpa.hibernate 属性一起)。这是由扩展org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration 的类引起的,并从类org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration 覆盖了方法protected Map&lt;String, Object&gt; getVendorProperties()。删除该类(毕竟这不是必需的)解决了问题并允许HibernateJpaConfiguration 类应用配置文件中的所有属性。

【讨论】:

    猜你喜欢
    • 2015-11-16
    • 2020-06-06
    • 1970-01-01
    • 2016-01-26
    • 2019-03-03
    • 2020-03-18
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多