有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java hibernate如何在JPA风格的引导过程中注册实体类

之前我使用的是hibernate本机引导,在这里我显式地调用addAnnotatedClass来逐个注册我的实体类

我正在迁移到JPA风格的引导,但我不清楚hibernate是如何识别和注册这些实体类的?我猜是通过@Entity注释,但是休眠是在对所有类进行全面扫描吗?我是否需要将实体类放入具有命名约定的特定包中,以使其正常工作


共 (1) 个答案

  1. # 1 楼答案

    我认为the official documentation有一个很好的解释:

    What Persistent Managed Classes Does This Persistence Unit Include?

    You can specify the persistent managed classes associated with a persistence unit by using one or more of the following:

    <mapping-file> element: specifies one or more object-relational mapping XML files (orm.xml files).

    <jar-file> element: specifies one or more JAR files that will be searched for classes.

    <class> element: specifies an explicit list of classes.

    The annotated managed persistence classes contained in the root of the persistence unit.

    The root of the persistence unit is the JAR file or directory, whose META-INF directory contains the persistence.xml file. To exclude managed persistence classes, add an <exclude-unlisted-classes> element to the persistence unit.

    基本上,它将扫描包含/META-INF/persistence.xml的JAR,寻找带有@Entity注释的类,或者您可以列出这些类并设置<exclude-unlisted-classes>true</exclude-unlisted-classes>,并且只使用列出的类

    例如:

    <persistence-unit name="postgresql-example">
        <class>org.hibernate.reactive.example.nativesql.Author</class>
        <class>org.hibernate.reactive.example.nativesql.Book</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        ...
    </persistence-unit>