Home >Java >javaTutorial >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
The answer is yes, but with certain conditions and limitations.
Using the "jar-file" Element
The persistence.xml file can include a
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
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!