I have very simple persistance.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
<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>
and it works.
But when I remove <class>
elements application doesn't see entities (all classes are annotated with @Entity
).
Is there any automatic mechanism to scan for @Entity
classes?
You can provide for
jar-file
element path to a folder with compiled classes. For example I added something like that when I prepared persistence.xml to some integration tests:I'm not sure this solution is under the spec but I think I can share for others.
dependency tree
my-entities.jar
Contains entity classes only. No
META-INF/persistence.xml
.my-services.jar
Depends on
my-entities
. Contains EJBs only.my-resources.jar
Depends on
my-services
. Contains resource classes andMETA-INF/persistence.xml
.problems
<jar-file/>
element inmy-resources
as the version-postfixed artifact name of a transient dependency?<jar-file/>
element's value and the actual transient dependency's one?solution
direct (redundant?) dependency and resource filtering
I put a property and a dependency in
my-resources/pom.xml
.Now get the
persistence.xml
ready for being filteredMaven Enforcer Plugin
With the
dependencyConvergence
rule, we can assure that themy-entities
' version is same in both direct and transitive.The persistence.xml has a
jar-file
that you can use. From the Java EE 5 tutorial:This file defines a persistence unit named
OrderManagement
, which uses a JTA-aware data sourcejdbc/MyOrderDB
. Thejar-file
andclass
elements specify managed persistence classes: entity classes, embeddable classes, and mapped superclasses. Thejar-file
element specifies JAR files that are visible to the packaged persistence unit that contain managed persistence classes, while theclass
element explicitly names managed persistence classes.In the case of Hibernate, have a look at the Chapter2. Setup and configuration too for more details.
EDIT: Actually, If you don't mind not being spec compliant, Hibernate supports auto-detection even in Java SE. To do so, add the
hibernate.archive.autodetection
property:For those running JPA in Spring, from version 3.1 onwards, you can set
packagesToScan
property underLocalContainerEntityManagerFactoryBean
and get rid of persistence.xml altogether.Here's the low-down