1

我们有一个关于 spring-boot 版本 1.5.2.RELEASE 的项目。

我们需要在 xml 中处理 hibernate 命名查询(java 注释中的命名查询不是我们的选择)。

为此,我们hbm.xml在目录中添加了所有文件(包含这些命名查询)src/main/resources

当我们的应用程序运行时,这不是问题。命名查询被正确提取。

但是,当我们编写集成测试用例时,它无法识别命名查询。

我们得到:

未找到命名查询异常

下面是我们的测试用例代码:

@RunWith(SpringRunner.class)
@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyIntegrationTest {
    @Autowired
    private TestRestTemplate template;

    @Test 
    public void checkRestService() throws Exception {
        ResponseEntity<String> response = template.getForEntity("/hello/1", String.class);
        assertTrue(response.getStatusCodeValue() == 200);
    }
}

如果我们将hbm.xml文件复制到 中src/test/resources directory,则hbm.xml文件会被正确拾取并且测试会正确运行。

无论如何,xml文件是直接从src/main/resouces文件夹中提取的,我们不必复制这些文件吗?

4

1 回答 1

0

我在 Spring Boot 2.1.3 中遇到了与您相同的问题,并通过将 application.properties 文件从 src/test/resources 文件夹移动到 src/main/resources 文件夹并将其重命名为 application-test.properties 来解决

以下是我的情况:

我的 Spring Boot 2.1.3 应用程序具有以下文件夹结构:

src/main
     +-- java (applcation java files)
     +-- resources
            +-- hibernate/MyMapping.hbm.xml
            +-- hibernate/MyMapping2.hbm.xml
            +-- application.properties (define the default / base attributes needed for my application)
            +-- application-dev.properties (define the development environment settings)
src/test
    +-- java (testing java files)
    +-- resources
            +-- application.properties (define the testing attributes)

每当我在 Eclipse / maven 中运行测试用例时,总是会出现错误:

未找到命名查询异常

我通过以下方式解决了这个问题:

  1. 将 src/test/resources/application.properties 文件移动到 src/main/resources/application-test.properties
  2. 在 src/main/resources/application.properties 中,定义以下属性:
spring.jpa.mapping-resources=hibernate/MyMapping.hbm.xml,hibernate/MyMapping2.hbm.xml
  1. 将注解添加@ActiveProfile("test")到所有测试类,以便它首先加载 src/main/resources 文件夹中的 application-test.properties 文件

在此之后,我的 SpringBoot 2 应用程序的测试用例可以在 Eclipse 和 maven 命令行中毫无问题地运行。

我的直觉是 Spring Boot/Hibernate 使用第一个加载的 application.properties 的位置作为基础来扫描/定位所有 hbm 文件。这可能与类加载器有关

于 2019-02-27T12:30:45.180 回答