spring-boot - Spring Boot : Setting Hibernate naming strategy with @DataJpaTest and Flyway

标签 spring-boot jpa junit h2 flyway

尝试在也使用 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。

Caused by: org.h2.jdbc.JdbcSQLException: Column "MYENTITY0_.COLUMNA" not found



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

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



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

最佳答案

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

关于spring-boot - Spring Boot : Setting Hibernate naming strategy with @DataJpaTest and Flyway,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54637399/

相关文章:

java - 如何创建 Wicket MarkupContainer 以在 JUnit 测试实用程序类中使用?

java - Spring boot - 不支持请求方法 'POST'。尝试了一切

postgresql - Hibernate 和 PostgreSQL : REPEATABLE_READ and use of @Version annotation to avoid write skews and other phenomena

jpa - 带输入参数的命名查询

java - 当我的代码不使用 ArrayLIst 时,为什么 ArrayList.java 会出现 NullPointerException 错误?

java - 尝试在 @After 方法中使用 @Test 方法生成的图像

java - Spring Boot 单元测试模块未检测到 Autowiring 的组件

spring-boot - 在Spring Boot中具有DSL的Apache Camel Rest端点将/camel添加到路径

java - 如何解决通过字段 'schedulerService' 表示的不满足的依赖关系?

Hibernate FetchMode.JOIN 在 Embeddable 中被忽略用作 ID