Well, if your classes are mapped via xml mappings (hbm
s) - you can add the documnets or jar files that include the xmls straight to the Configuration
instance using config.addJar(myJarFile)
and config.add(myXmlFile)
.
However, if you want your annotated classes to be scanned - I know of no such straightforward option through Hibernate (addPackage
adds metadata and not classes).
You may implement your own scan logic and add all annotated classes with config.addAnnotatedClass(myAnnotatedClass)
(or perhaps do it per specific packages you know for containing you ORM classes and thus maybe save some time).
UPDATE 2
Oh, even better, you can just iterate the persistence unit's ManagedType
s via getManagedTypes()
:
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory( unitName, config.getProperties() );
final Set<ManagedType<?>> managedTypes =
entityManagerFactory.getMetamodel().getManagedTypes();
for ( ManagedType<?> managedType : managedTypes ) {
final Class<?> javaType = managedType.getJavaType();
config.addAnnotatedClass( javaType );
}
UPDATE
You can determine the PersistenceUnit
of each Entity
- without parsing the xml - by checking against the relevant EntityManagerFactory
:
Class aClass = ... // get the class from your scanning
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory( unitName, config.getProperties() );
ManagedType<?> managedType = null;
try {
managedType = entityManagerFactory.getMetamodel().managedType( aClass );
} catch ( IllegalArgumentException e ) {
// happens when aClass isn't a type managed by the persistence unit
}
if ( managedType != null ) {
config.addAnnotatedClass( aClass );
}
Make sure to use different Configuration
instances for each persistence unit. Otherwise, annotated classes would just accumulate and so also the DDL.
I tried it and it worked great - printed two distinct DDLs for two different persistence units.