hibernate jpa单元测试autodection不起作用

use*_*201 5 jpa

我在persistence.xml中有以下内容

<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
    <class>com.merc.model.log.EventLogging</class>
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    <properties>
        <!-- Scan for annotated classes and Hibernate mapping XML files -->
        <property name="hibernate.archive.autodetection" value="class"/>
    </properties>
</persistence-unit>
Run Code Online (Sandbox Code Playgroud)

如果我注释掉com.merc.model.log.EventLogging,我会得到Unknown实体异常.

关于为什么自动检测不起作用的任何想法

axt*_*avt 14

这可能是由于默认情况下自动检测适用于所在的同一类路径项内的类persistence.xml.

因此,您有代码本身和测试的单独目标文件夹(例如,如果您使用默认配置的Maven),并且如果persistence.xml在编译后最终在测试的目标文件夹中,主目标文件夹中的类将不会被发现.

您可以使用<jar-file>元素指向应搜索实体的其他类路径项.

如果您使用Maven,您可以使用资源过滤以优雅的方式完成:

persistence.xml:

<jar-file>${project.build.outputDirectory}</jar-file>
Run Code Online (Sandbox Code Playgroud)

pom.xml:

<build>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
            <filtering>true</filtering>
        </testResource>
    </testResources>
</build>
Run Code Online (Sandbox Code Playgroud)