Hibernate在测试中找不到实体。

huangapple go评论81阅读模式
英文:

Hibernate doesn't find entities in test

问题

我有一个由Maven构建的JDK11项目,充分利用了Java 9引入的JPMS。

我想编写集成测试,在集成测试中我使用嵌入式H2数据库。我的JPA提供者是Hibernate 5.4.9。

由于H2数据库仅在测试期间使用,我首先尝试将persistence.xml放入测试资源文件夹中。

问题在于Hibernate仅在test-classes文件夹中查找实体,完全忽略了主要的类,而我的实体就在主要类中。因此,我的测试失败了,因为它找不到我尝试使用的实体。

如果我将持久性单元声明复制到主要资源文件夹中,一切正常工作,然而,我不想这样做,因为Hibernate仅是一个测试依赖,我不想使用不存在的类。

为什么突然出现了这个问题?我以前从未遇到过这个问题(主要是在Java 8和Hibernate 5.3中)。

我能否在无需将persistence.xml复制到主要资源的情况下使我的实体被检测到?我也不想手动列出我的实体。

英文:

I have a JDK11 project built by Maven, making full use of the JPMS introduced in Java 9.

I'd like to write integration tests, where I use an embedded H2 database. My JPA provider is Hibernate 5.4.9.

Since the H2 database is only used during testing, I first tried putting the persistence.xml in the test resources folder.

The problem with this is that Hibernate is looking for entities in the test-classes folder only and completely ignores the main classes, where my entities are. So my test fails, because it doesn't find the entities I'm trying to use.

If I copy the persistence unit declaration to the main resources folder, everything works correctly, however, I wouldn't like to have it there because Hibernate is only a test dependency and I wouldn't like to use non-existing classes.

Why is this issue suddenly happening? I never had this issue come up before (mainly with Java 8 and Hibernate 5.3).

Can I manage to have my entities detected without having to copy my persistence.xml to my main resources? I also wouldn't like to list my entities manually.

答案1

得分: 1

我解决了。我忘记在我的测试persistence.xml中的persistence-unit声明中添加以下行:

<jar-file>${project.build.outputDirectory}</jar-file>

英文:

I worked it out. I forgot to add the following line to the persistence-unit declaration in my test persistence.xml:

&lt;jar-file&gt;${project.build.outputDirectory}&lt;/jar-file&gt;

huangapple
  • 本文由 发表于 2020年4月10日 01:44:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/61127082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定