Home >Java >javaTutorial >Can JPA Automatically Scan for Entities Annotated with @Entity?

Can JPA Automatically Scan for Entities Annotated with @Entity?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-04 15:06:141093browse

Can JPA Automatically Scan for Entities Annotated with @Entity?

Automatic Entity Scanning in persistence.xml

In Java Persistence API (JPA), entities are typically declared in the persistence.xml deployment descriptor using the element. However, is there a mechanism to automatically scan for entities annotated with @Entity instead?

The answer is yes, but with certain conditions and limitations.

Using the "jar-file" Element

The persistence.xml file can include a element to specify the JAR file(s) containing the entity classes. The JPA provider will then scan the specified JAR file(s) for entities. This is defined in the JPA specification and is supported by most JPA providers, including Hibernate.

Example:

<persistence>
    <persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
        <jar-file>MyEventractor.jar</jar-file>
        <!-- Explicit listing of entity classes is still allowed -->
        <class>pl.michalmech.eventractor.domain.User</class>
        <class>pl.michalmech.eventractor.domain.Address</class>
        <class>pl.michalmech.eventractor.domain.City</class>
        <class>pl.michalmech.eventractor.domain.Country</class>

        <properties>
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

Hibernate-Specific Auto-Detection (Java SE)

In Hibernate specifically, even if the JPA specification doesn't require it, auto-detection of entities is supported even in Java SE applications. To enable this, add the following property to your persistence unit:

<property name="hibernate.archive.autodetection" value="class, hbm" />

This allows Hibernate to scan for classes annotated with @Entity and for Hibernate mapping files (.hbm.xml) in the JAR file specified by the element.

Limitations

It's important to note that relying on automatic entity scanning may not always be the best practice. In scenarios where classpath visibility is dynamic or there are multiple modules with conflicting entity definitions, explicit class listing can provide better control.

The above is the detailed content of Can JPA Automatically Scan for Entities Annotated with @Entity?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn