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