1 package de.juplo.plugins.hibernate;
4 import com.pyx4j.log4j.MavenLogAppender;
6 import java.io.FileInputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
10 import java.net.URLClassLoader;
11 import java.security.NoSuchAlgorithmException;
12 import java.util.Collections;
13 import java.util.HashSet;
14 import java.util.Iterator;
15 import java.util.LinkedList;
16 import java.util.List;
18 import java.util.Map.Entry;
19 import java.util.Properties;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23 import javax.persistence.Embeddable;
24 import javax.persistence.Entity;
25 import javax.persistence.MappedSuperclass;
26 import javax.persistence.spi.PersistenceUnitTransactionType;
27 import org.apache.maven.artifact.Artifact;
28 import org.apache.maven.model.Resource;
29 import org.apache.maven.plugin.AbstractMojo;
30 import org.apache.maven.plugin.MojoExecutionException;
31 import org.apache.maven.plugin.MojoFailureException;
32 import org.apache.maven.project.MavenProject;
33 import org.hibernate.boot.MetadataBuilder;
34 import org.hibernate.boot.MetadataSources;
35 import org.hibernate.boot.cfgxml.internal.ConfigLoader;
36 import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
37 import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
38 import org.hibernate.boot.registry.BootstrapServiceRegistry;
39 import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
40 import org.hibernate.boot.registry.StandardServiceRegistry;
41 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
42 import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
43 import org.hibernate.boot.registry.selector.spi.StrategySelector;
44 import org.hibernate.boot.spi.MetadataImplementor;
45 import static org.hibernate.cfg.AvailableSettings.DIALECT;
46 import static org.hibernate.cfg.AvailableSettings.DRIVER;
47 import static org.hibernate.cfg.AvailableSettings.FORMAT_SQL;
48 import static org.hibernate.cfg.AvailableSettings.HBM2DLL_CREATE_NAMESPACES;
49 import static org.hibernate.cfg.AvailableSettings.IMPLICIT_NAMING_STRATEGY;
50 import static org.hibernate.cfg.AvailableSettings.PASS;
51 import static org.hibernate.cfg.AvailableSettings.PHYSICAL_NAMING_STRATEGY;
52 import static org.hibernate.cfg.AvailableSettings.SHOW_SQL;
53 import static org.hibernate.cfg.AvailableSettings.USER;
54 import static org.hibernate.cfg.AvailableSettings.URL;
55 import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
56 import org.hibernate.internal.util.config.ConfigurationException;
57 import static org.hibernate.jpa.AvailableSettings.JDBC_DRIVER;
58 import static org.hibernate.jpa.AvailableSettings.JDBC_PASSWORD;
59 import static org.hibernate.jpa.AvailableSettings.JDBC_URL;
60 import static org.hibernate.jpa.AvailableSettings.JDBC_USER;
61 import org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor;
62 import org.hibernate.jpa.boot.internal.PersistenceXmlParser;
63 import org.hibernate.jpa.boot.spi.ProviderChecker;
64 import org.scannotation.AnnotationDB;
68 * Baseclass with common attributes and methods.
70 * @phase process-classes
72 * @requiresDependencyResolution runtime
74 public abstract class AbstractSchemaMojo extends AbstractMojo
76 public final static String EXPORT = "hibernate.schema.export";
77 public final static String DELIMITER = "hibernate.schema.delimiter";
78 public final static String OUTPUTDIRECTORY = "project.build.outputDirectory";
79 public final static String SCAN_DEPENDENCIES = "hibernate.schema.scan.dependencies";
80 public final static String SCAN_TESTCLASSES = "hibernate.schema.scan.test_classes";
81 public final static String TEST_OUTPUTDIRECTORY = "project.build.testOutputDirectory";
82 public final static String SKIPPED = "hibernate.schema.skipped";
84 private final static Pattern SPLIT = Pattern.compile("[^,\\s]+");
90 * Only needed internally.
92 * @parameter property="project"
96 private MavenProject project;
101 * Only needed internally.
103 * @parameter property="project.build.directory"
107 String buildDirectory;
110 /** Parameters to configure the genaration of the SQL *********************/
113 * Export the database-schma to the database.
114 * If set to <code>false</code>, only the SQL-script is created and the
115 * database is not touched.
117 * <strong>Important:</strong>
118 * This configuration value can only be configured through the
119 * <code>pom.xml</code>, or by the definition of a system-property, because
120 * it is not known by Hibernate nor JPA and, hence, not picked up from
121 * their configuration!
123 * @parameter property="hibernate.schema.export" default-value="true"
131 * If set to <code>true</code>, the execution is skipped.
133 * A skipped execution is signaled via the maven-property
134 * <code>${hibernate.export.skipped}</code>.
136 * The execution is skipped automatically, if no modified or newly added
137 * annotated classes are found and the dialect was not changed.
139 * <strong>Important:</strong>
140 * This configuration value can only be configured through the
141 * <code>pom.xml</code>, or by the definition of a system-property, because
142 * it is not known by Hibernate nor JPA and, hence, not picked up from
143 * their configuration!
145 * @parameter property="hibernate.schema.skip" default-value="${maven.test.skip}"
148 private boolean skip;
153 * Force execution, even if no modified or newly added annotated classes
154 * where found and the dialect was not changed.
156 * <code>skip</code> takes precedence over <code>force</code>.
158 * <strong>Important:</strong>
159 * This configuration value can only be configured through the
160 * <code>pom.xml</code>, or by the definition of a system-property, because
161 * it is not known by Hibernate nor JPA and, hence, not picked up from
162 * their configuration!
164 * @parameter property="hibernate.schema.force" default-value="false"
167 private boolean force;
172 * @parameter property="hibernate.dialect"
175 private String dialect;
178 * Delimiter in output-file.
180 * <strong>Important:</strong>
181 * This configuration value can only be configured through the
182 * <code>pom.xml</code>, or by the definition of a system-property, because
183 * it is not known by Hibernate nor JPA and, hence, not picked up from
184 * their configuration!
186 * @parameter property="hibernate.schema.delimiter" default-value=";"
192 * Show the generated SQL in the command-line output.
194 * @parameter property="hibernate.show_sql"
200 * Format output-file.
202 * @parameter property="hibernate.format_sql"
208 * Specifies whether to automatically create also the database schema/catalog.
210 * @parameter property="hibernate.hbm2dll.create_namespaces" default-value="false"
213 Boolean createNamespaces;
216 * Implicit naming strategy
218 * @parameter property="hibernate.implicit_naming_strategy"
221 private String implicitNamingStrategy;
224 * Physical naming strategy
226 * @parameter property="hibernate.physical_naming_strategy"
229 private String physicalNamingStrategy;
232 * Classes-Directory to scan.
234 * This parameter defaults to the maven build-output-directory for classes.
235 * Additionally, all dependencies are scanned for annotated classes.
237 * <strong>Important:</strong>
238 * This configuration value can only be configured through the
239 * <code>pom.xml</code>, or by the definition of a system-property, because
240 * it is not known by Hibernate nor JPA and, hence, not picked up from
241 * their configuration!
243 * @parameter property="project.build.outputDirectory"
246 private String outputDirectory;
249 * Dependency-Scopes, that should be scanned for annotated classes.
251 * By default, only dependencies in the scope <code>compile</code> are
252 * scanned for annotated classes. Multiple scopes can be seperated by
253 * white space or commas.
255 * If you do not want any dependencies to be scanned for annotated
256 * classes, set this parameter to <code>none</code>.
258 * The plugin does not scan for annotated classes in transitive
259 * dependencies. If some of your annotated classes are hidden in a
260 * transitive dependency, you can simply add that dependency explicitly.
262 * @parameter property="hibernate.schema.scan.dependencies" default-value="compile"
265 private String scanDependencies;
268 * Whether to scan test-classes too, or not.
270 * If this parameter is set to <code>true</code> the test-classes of the
271 * artifact will be scanned for hibernate-annotated classes additionally.
273 * <strong>Important:</strong>
274 * This configuration value can only be configured through the
275 * <code>pom.xml</code>, or by the definition of a system-property, because
276 * it is not known by Hibernate nor JPA and, hence, not picked up from
277 * their configuration!
279 * @parameter property="hibernate.schema.scan.test_classes" default-value="false"
282 private Boolean scanTestClasses;
285 * Test-Classes-Directory to scan.
287 * This parameter defaults to the maven build-output-directory for
290 * This parameter is only used, when <code>scanTestClasses</code> is set
291 * to <code>true</code>!
293 * <strong>Important:</strong>
294 * This configuration value can only be configured through the
295 * <code>pom.xml</code>, or by the definition of a system-property, because
296 * it is not known by Hibernate nor JPA and, hence, not picked up from
297 * their configuration!
299 * @parameter property="project.build.testOutputDirectory"
302 private String testOutputDirectory;
305 /** Conection parameters *************************************************/
310 * @parameter property="hibernate.connection.driver_class"
313 private String driver;
318 * @parameter property="hibernate.connection.url"
326 * @parameter property="hibernate.connection.username"
329 private String username;
334 * @parameter property="hibernate.connection.password"
337 private String password;
340 /** Parameters to locate configuration sources ****************************/
343 * Path to a file or name of a ressource with hibernate properties.
344 * If this parameter is specified, the plugin will try to load configuration
345 * values from a file with the given path or a ressource on the classpath with
346 * the given name. If both fails, the execution of the plugin will fail.
348 * If this parameter is not set the plugin will load configuration values
349 * from a ressource named <code>hibernate.properties</code> on the classpath,
350 * if it is present, but will not fail if there is no such ressource.
352 * During ressource-lookup, the test-classpath takes precedence.
357 private String hibernateProperties;
360 * Path to Hibernate configuration file (.cfg.xml).
361 * If this parameter is specified, the plugin will try to load configuration
362 * values from a file with the given path or a ressource on the classpath with
363 * the given name. If both fails, the execution of the plugin will fail.
365 * If this parameter is not set the plugin will load configuration values
366 * from a ressource named <code>hibernate.cfg.xml</code> on the classpath,
367 * if it is present, but will not fail if there is no such ressource.
369 * During ressource-lookup, the test-classpath takes precedence.
371 * Settings in this file will overwrite settings in the properties file.
376 private String hibernateConfig;
379 * Name of the persistence-unit.
380 * If this parameter is specified, the plugin will try to load configuration
381 * values from a persistence-unit with the specified name. If no such
382 * persistence-unit can be found, the plugin will throw an exception.
384 * If this parameter is not set and there is only one persistence-unit
385 * available, that unit will be used automatically. But if this parameter is
386 * not set and there are multiple persistence-units available on,
387 * the class-path, the execution of the plugin will fail.
389 * Settings in this file will overwrite settings in the properties or the
390 * configuration file.
395 private String persistenceUnit;
398 * List of Hibernate-Mapping-Files (XML).
399 * Multiple files can be separated with white-spaces and/or commas.
401 * @parameter property="hibernate.mapping"
404 private String mappings;
408 public final void execute(String filename)
410 MojoFailureException,
411 MojoExecutionException
415 getLog().info("Execution of hibernate-maven-plugin was skipped!");
416 project.getProperties().setProperty(SKIPPED, "true");
420 ModificationTracker tracker;
423 tracker = new ModificationTracker(buildDirectory, filename, getLog());
425 catch (NoSuchAlgorithmException e)
427 throw new MojoFailureException("Digest-Algorithm MD5 is missing!", e);
430 SimpleConnectionProvider connectionProvider =
431 new SimpleConnectionProvider(getLog());
435 /** Start extended logging */
436 MavenLogAppender.startPluginLog(this);
438 /** Load checksums for old mapping and configuration */
441 /** Create a BootstrapServiceRegistry with special ClassLoader */
442 BootstrapServiceRegistry bootstrapServiceRegitry =
443 new BootstrapServiceRegistryBuilder()
444 .applyClassLoader(createClassLoader())
446 ClassLoaderService classLoaderService =
447 bootstrapServiceRegitry.getService(ClassLoaderService.class);
449 Properties properties = new Properties();
450 ConfigLoader configLoader = new ConfigLoader(bootstrapServiceRegitry);
452 /** Loading and merging configuration */
453 properties.putAll(loadProperties(configLoader));
454 properties.putAll(loadConfig(configLoader));
455 properties.putAll(loadPersistenceUnit(classLoaderService, properties));
457 /** Overwriting/Completing configuration */
458 configure(properties, tracker);
460 /** Check configuration for modifications */
461 if(tracker.track(properties))
462 getLog().debug("Configuration has changed.");
464 getLog().debug("Configuration unchanged.");
466 /** Configure Hibernate */
467 StandardServiceRegistry serviceRegistry =
468 new StandardServiceRegistryBuilder(bootstrapServiceRegitry)
469 .applySettings(properties)
470 .addService(ConnectionProvider.class, connectionProvider)
474 MetadataSources sources = new MetadataSources(serviceRegistry);
475 addAnnotatedClasses(sources, classLoaderService, tracker);
476 addMappings(sources, tracker);
478 /** Skip execution, if mapping and configuration is unchanged */
479 if (!tracker.modified())
482 "Mapping and configuration unchanged."
485 getLog().info("Schema generation is forced!");
488 getLog().info("Skipping schema generation!");
489 project.getProperties().setProperty(SKIPPED, "true");
495 /** Create a connection, if sufficient configuration infromation is available */
496 connectionProvider.open(classLoaderService, properties);
498 MetadataBuilder metadataBuilder = sources.getMetadataBuilder();
500 StrategySelector strategySelector =
501 serviceRegistry.getService(StrategySelector.class);
503 if (properties.containsKey(IMPLICIT_NAMING_STRATEGY))
505 metadataBuilder.applyImplicitNamingStrategy(
506 strategySelector.resolveStrategy(
507 ImplicitNamingStrategy.class,
508 properties.getProperty(IMPLICIT_NAMING_STRATEGY)
513 if (properties.containsKey(PHYSICAL_NAMING_STRATEGY))
515 metadataBuilder.applyPhysicalNamingStrategy(
516 strategySelector.resolveStrategy(
517 PhysicalNamingStrategy.class,
518 properties.getProperty(PHYSICAL_NAMING_STRATEGY)
523 build((MetadataImplementor)metadataBuilder.build());
527 /** Remember mappings and configuration */
530 /** Close the connection - if one was opened */
531 connectionProvider.close();
533 /** Stop Log-Capturing */
534 MavenLogAppender.endPluginLog(this);
539 abstract void build(MetadataImplementor metadata)
541 MojoFailureException,
542 MojoExecutionException;
545 private URLClassLoader createClassLoader() throws MojoExecutionException
549 getLog().debug("Creating ClassLoader for project-dependencies...");
550 List<String> classpathFiles = project.getCompileClasspathElements();
552 classpathFiles.addAll(project.getTestClasspathElements());
553 List<URL> urls = new LinkedList<URL>();
555 file = new File(testOutputDirectory);
558 getLog().info("creating test-output-directory: " + testOutputDirectory);
561 urls.add(file.toURI().toURL());
562 file = new File(outputDirectory);
565 getLog().info("creating output-directory: " + outputDirectory);
568 urls.add(file.toURI().toURL());
569 for (String pathElement : classpathFiles)
571 getLog().debug("Dependency: " + pathElement);
572 urls.add(new File(pathElement).toURI().toURL());
576 urls.toArray(new URL[urls.size()]),
577 getClass().getClassLoader()
582 getLog().error("Error while creating ClassLoader!", e);
583 throw new MojoExecutionException(e.getMessage());
587 private Map loadProperties(ConfigLoader configLoader)
589 MojoExecutionException
591 /** Try to read configuration from properties-file */
592 if (hibernateProperties == null)
596 return configLoader.loadProperties("hibernate.properties");
598 catch (ConfigurationException e)
600 getLog().debug(e.getMessage());
601 return Collections.EMPTY_MAP;
608 File file = new File(hibernateProperties);
611 getLog().info("Reading settings from file " + hibernateProperties + "...");
612 return configLoader.loadProperties(file);
615 return configLoader.loadProperties(hibernateProperties);
617 catch (ConfigurationException e)
619 getLog().error("Error while reading properties!", e);
620 throw new MojoExecutionException(e.getMessage());
625 private Map loadConfig(ConfigLoader configLoader)
626 throws MojoExecutionException
628 /** Try to read configuration from configuration-file */
629 if (hibernateConfig == null)
635 .loadConfigXmlResource("hibernate.cfg.xml")
636 .getConfigurationValues();
638 catch (ConfigurationException e)
640 getLog().debug(e.getMessage());
641 return Collections.EMPTY_MAP;
648 File file = new File(hibernateConfig);
651 getLog().info("Reading configuration from file " + hibernateConfig + "...");
652 return configLoader.loadConfigXmlFile(file).getConfigurationValues();
657 .loadConfigXmlResource(hibernateConfig)
658 .getConfigurationValues();
660 catch (ConfigurationException e)
662 getLog().error("Error while reading configuration!", e);
663 throw new MojoExecutionException(e.getMessage());
668 private void configure(Properties properties, ModificationTracker tracker)
669 throws MojoFailureException
672 * Special treatment for the configuration-value "export": if it is
673 * switched to "true", the genearation fo the schema should be forced!
675 if (tracker.check(EXPORT, export.toString()) && export)
679 * Configure the generation of the SQL.
680 * Overwrite values from properties-file if the configuration parameter is
681 * known to Hibernate.
683 dialect = configure(properties, dialect, DIALECT);
684 tracker.track(DELIMITER, delimiter); // << not reflected in hibernate configuration!
685 format = configure(properties, format, FORMAT_SQL);
686 createNamespaces = configure(properties, createNamespaces, HBM2DLL_CREATE_NAMESPACES);
687 implicitNamingStrategy = configure(properties, implicitNamingStrategy, IMPLICIT_NAMING_STRATEGY);
688 physicalNamingStrategy = configure(properties, physicalNamingStrategy, PHYSICAL_NAMING_STRATEGY);
689 tracker.track(OUTPUTDIRECTORY, outputDirectory); // << not reflected in hibernate configuration!
690 tracker.track(SCAN_DEPENDENCIES, scanDependencies); // << not reflected in hibernate configuration!
691 tracker.track(SCAN_TESTCLASSES, scanTestClasses.toString()); // << not reflected in hibernate configuration!
692 tracker.track(TEST_OUTPUTDIRECTORY, testOutputDirectory); // << not reflected in hibernate configuration!
695 * Special treatment for the configuration-value "show": a change of its
696 * configured value should not lead to a regeneration of the database
700 show = Boolean.valueOf(properties.getProperty(SHOW_SQL));
702 properties.setProperty(SHOW_SQL, show.toString());
705 * Configure the connection parameters.
706 * Overwrite values from properties-file.
708 driver = configure(properties, driver, DRIVER, JDBC_DRIVER);
709 url = configure(properties, url, URL, JDBC_URL);
710 username = configure(properties, username, USER, JDBC_USER);
711 password = configure(properties, password, PASS, JDBC_PASSWORD);
713 if (properties.isEmpty())
715 getLog().error("No properties set!");
716 throw new MojoFailureException("Hibernate configuration is missing!");
719 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
720 for (Entry<Object,Object> entry : properties.entrySet())
721 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
724 private String configure(
725 Properties properties,
728 String alternativeKey
731 value = configure(properties, value, key);
733 return properties.getProperty(alternativeKey);
735 if (properties.containsKey(alternativeKey))
738 "Ignoring property " + alternativeKey + "=" +
739 properties.getProperty(alternativeKey) + " in favour for property " +
740 key + "=" + properties.getProperty(key)
742 properties.remove(alternativeKey);
744 return properties.getProperty(alternativeKey);
747 private String configure(Properties properties, String value, String key)
751 if (properties.containsKey(key))
753 "Overwriting property " + key + "=" + properties.getProperty(key) +
754 " with the value " + value
757 getLog().debug("Using the value " + value + " for property " + key);
758 properties.setProperty(key, value);
760 return properties.getProperty(key);
763 private boolean configure(Properties properties, Boolean value, String key)
767 if (properties.containsKey(key))
769 "Overwriting property " + key + "=" + properties.getProperty(key) +
770 " with the value " + value
773 getLog().debug("Using the value " + value + " for property " + key);
774 properties.setProperty(key, value.toString());
776 return Boolean.valueOf(properties.getProperty(key));
779 private void addMappings(MetadataSources sources, ModificationTracker tracker)
780 throws MojoFailureException
782 getLog().debug("Adding explicitly configured mappings...");
783 if (mappings != null)
787 for (String filename : mappings.split("[\\s,]+"))
789 // First try the filename as absolute/relative path
790 File file = new File(filename);
793 // If the file was not found, search for it in the resource-directories
794 for (Resource resource : project.getResources())
796 file = new File(resource.getDirectory() + File.separator + filename);
803 if (file.isDirectory())
804 // TODO: add support to read all mappings under a directory
805 throw new MojoFailureException(file.getAbsolutePath() + " is a directory");
806 if (tracker.track(filename, new FileInputStream(file)))
807 getLog().debug("Found new or modified mapping-file: " + filename);
809 getLog().debug("mapping-file unchanged: " + filename);
811 sources.addFile(file);
814 throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
817 catch (IOException e)
819 throw new MojoFailureException("Cannot calculate MD5 sums!", e);
824 private void addAnnotatedClasses(
825 MetadataSources sources,
826 ClassLoaderService classLoaderService,
827 ModificationTracker tracker
830 MojoFailureException,
831 MojoExecutionException
836 AnnotationDB db = new AnnotationDB();
839 dir = new File(outputDirectory);
842 getLog().info("Scanning directory " + dir.getAbsolutePath() + " for annotated classes...");
843 URL dirUrl = dir.toURI().toURL();
844 db.scanArchives(dirUrl);
849 dir = new File(testOutputDirectory);
852 getLog().info("Scanning directory " + dir.getAbsolutePath() + " for annotated classes...");
853 URL dirUrl = dir.toURI().toURL();
854 db.scanArchives(dirUrl);
858 if (scanDependencies != null)
860 Matcher matcher = SPLIT.matcher(scanDependencies);
861 while (matcher.find())
863 getLog().info("Scanning dependencies for scope " + matcher.group());
864 for (Artifact artifact : project.getDependencyArtifacts())
866 if (!artifact.getScope().equalsIgnoreCase(matcher.group()))
868 if (artifact.getFile() == null)
870 getLog().warn("Cannot scan dependency " + artifact.getId() + ": no JAR-file available!");
873 getLog().info("Scanning dependency " + artifact.getId() + " for annotated classes...");
874 db.scanArchives(artifact.getFile().toURI().toURL());
879 Set<String> classes = new HashSet<String>();
880 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
881 classes.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
882 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
883 classes.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
884 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
885 classes.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
887 Set<String> packages = new HashSet<String>();
889 for (String name : classes)
891 Class<?> annotatedClass = classLoaderService.classForName(name);
892 String packageName = annotatedClass.getPackage().getName();
893 if (!packages.contains(packageName))
896 annotatedClass.getResourceAsStream("package-info.class");
899 // No compiled package-info available: no package-level annotations!
900 getLog().debug("Package " + packageName + " is not annotated.");
904 if (tracker.track(packageName, is))
905 getLog().debug("New or modified package: " + packageName);
907 getLog().debug("Unchanged package: " + packageName);
908 getLog().info("Adding annotated package " + packageName);
909 sources.addPackage(packageName);
911 packages.add(packageName);
913 String resourceName = annotatedClass.getName();
915 resourceName.substring(
916 resourceName.lastIndexOf(".") + 1,
917 resourceName.length()
921 .getResourceAsStream(resourceName);
922 if (tracker.track(name, is))
923 getLog().debug("New or modified class: " + name);
925 getLog().debug("Unchanged class: " + name);
926 getLog().info("Adding annotated class " + annotatedClass);
927 sources.addAnnotatedClass(annotatedClass);
932 getLog().error("Error while scanning!", e);
933 throw new MojoFailureException(e.getMessage());
937 private Properties loadPersistenceUnit(
938 ClassLoaderService classLoaderService,
939 Properties properties
944 PersistenceXmlParser parser =
945 new PersistenceXmlParser(
947 PersistenceUnitTransactionType.RESOURCE_LOCAL
950 List<ParsedPersistenceXmlDescriptor> units = parser.doResolve(properties);
952 if (persistenceUnit == null)
954 switch (units.size())
957 getLog().info("Found no META-INF/persistence.xml.");
958 return new Properties();
960 getLog().info("Using persistence-unit " + units.get(0).getName());
961 return units.get(0).getProperties();
963 StringBuilder builder = new StringBuilder();
964 builder.append("No name provided and multiple persistence units found: ");
965 Iterator<ParsedPersistenceXmlDescriptor> it = units.iterator();
966 builder.append(it.next().getName());
969 builder.append(", ");
970 builder.append(it.next().getName());
973 throw new MojoFailureException(builder.toString());
977 for (ParsedPersistenceXmlDescriptor unit : units)
979 getLog().debug("Found persistence-unit " + unit.getName());
980 if (!unit.getName().equals(persistenceUnit))
983 // See if we (Hibernate) are the persistence provider
984 if (!ProviderChecker.isProvider(unit, properties))
986 getLog().debug("Wrong provider: " + unit.getProviderClassName());
990 getLog().info("Using persistence-unit " + unit.getName());
991 return unit.getProperties();
994 throw new MojoFailureException("Could not find persistence-unit " + persistenceUnit);