1 package de.juplo.plugins.hibernate4;
4 * Copyright 2001-2005 The Apache Software Foundation.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 import com.pyx4j.log4j.MavenLogAppender;
20 import org.apache.maven.plugin.AbstractMojo;
21 import org.apache.maven.plugin.MojoExecutionException;
22 import org.apache.maven.plugin.MojoFailureException;
23 import org.apache.maven.project.MavenProject;
24 import org.hibernate.cfg.Configuration;
25 import org.hibernate.envers.configuration.AuditConfiguration;
26 import org.hibernate.tool.hbm2ddl.SchemaExport;
27 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
28 import org.hibernate.tool.hbm2ddl.Target;
29 import org.scannotation.AnnotationDB;
31 import javax.persistence.Embeddable;
32 import javax.persistence.Entity;
33 import javax.persistence.MappedSuperclass;
35 import java.math.BigInteger;
37 import java.net.URLClassLoader;
38 import java.security.MessageDigest;
41 import java.util.Map.Entry;
42 import java.util.logging.Logger;
46 * Goal which extracts the hibernate-mapping-configuration and
47 * exports an according SQL-database-schema.
50 * @phase process-classes
52 * @requiresDependencyResolution runtime
54 public class Hbm2DdlMojo extends AbstractMojo
56 public final static String EXPORT_SKIPPED_PROPERTY = "hibernate.export.skipped";
58 public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
59 public final static String URL = "hibernate.connection.url";
60 public final static String USERNAME = "hibernate.connection.username";
61 public final static String PASSWORD = "hibernate.connection.password";
62 public final static String DIALECT = "hibernate.dialect";
63 public final static String ENVERS = "hibernate.export.envers";
65 private final static String MD5S = "schema.md5s";
70 * Only needed internally.
72 * @parameter expression="${project}"
76 private MavenProject project;
81 * Only needed internally.
83 * @parameter expression="${project.build.directory}"
87 private String buildDirectory;
90 * Classes-Directory to scan.
92 * This parameter defaults to the maven build-output-directory for classes.
93 * Additonally, all dependencies are scanned for annotated classes.
95 * @parameter expression="${project.build.outputDirectory}"
97 private String outputDirectory;
100 * Wether to scan test-classes too, or not.
102 * If this parameter is set to <code>true</code> the test-classes of the
103 * artifact will be scanned for hibernate-annotated classes additionally.
105 * @parameter expression="${hibernate.export.scann_testclasses}" default-value="false"
107 private boolean scanTestClasses;
110 * Test-Classes-Directory to scan.
112 * This parameter defaults to the maven build-output-directory for
115 * This parameter is only used, when <code>scanTestClasses</code> is set
116 * to <code>true</code>!
118 * @parameter expression="${project.build.testOutputDirectory}"
120 private String testOutputDirectory;
125 * If set to <code>true</code>, the execution is skipped.
127 * A skipped excecution is signaled via the maven-property
128 * <code>${hibernate.export.skipped}</code>.
130 * The excecution is skipped automatically, if no modified or newly added
131 * annotated classes are found and the dialect was not changed.
133 * @parameter expression="${maven.test.skip}" default-value="false"
135 private boolean skip;
140 * Force execution, even if no modified or newly added annotated classes
141 * where found and the dialect was not changed.
143 * <code>skip</code> takes precedence over <code>force</code>.
145 * @parameter expression="${hibernate.export.force}" default-value="false"
147 private boolean force;
152 * @parameter expression="${hibernate.connection.driver_class}
154 private String driverClassName;
159 * @parameter expression="${hibernate.connection.url}"
166 * @parameter expression="${hibernate.connection.username}"
168 private String username;
173 * @parameter expression="${hibernate.connection.password}"
175 private String password;
180 * @parameter expression="${hibernate.dialect}"
182 private String hibernateDialect;
185 * Path to Hibernate configuration file.
187 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
189 private String hibernateProperties;
192 * Target of execution:
194 * <li><strong>NONE</strong> do nothing - just validate the configuration (forces excecution, signals skip)</li>
195 * <li><strong>EXPORT</strong> create database (<strong>DEFAULT!</strong>. forces excecution, signals skip)</li>
196 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
197 * <li><strong>BOTH</strong></li>
200 * @parameter expression="${hibernate.export.target}" default-value="EXPORT"
202 private String target;
207 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
208 * <li><strong>CREATE</strong> create database-schema</li>
209 * <li><strong>DROP</strong> drop database-schema</li>
210 * <li><strong>BOTH</strong> (<strong>DEFAULT!</strong>)</li>
213 * @parameter expression="${hibernate.export.type}" default-value="BOTH"
220 * @parameter expression="${hibernate.export.schema.filename}" default-value="${project.build.directory}/schema.sql"
222 private String outputFile;
225 * Delimiter in output-file.
227 * @parameter expression="${hibernate.export.schema.delimiter}" default-value=";"
229 private String delimiter;
232 * Format output-file.
234 * @parameter expression="${hibernate.export.schema.format}" default-value="true"
236 private boolean format;
239 * Generate envers schema for auditing tables.
241 * @parameter expression="${hibernate.export.envers}" default-value="false"
243 private Boolean envers;
246 * Transient attribute, used only for knowing if the schema has changed since it was last run.
248 private boolean modified;
251 public void execute()
253 MojoFailureException,
254 MojoExecutionException
258 getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
259 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
263 File dir = new File(outputDirectory);
265 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
267 Map<String,String> md5s;
269 File saved = new File(buildDirectory + File.separator + MD5S);
275 FileInputStream fis = new FileInputStream(saved);
276 ObjectInputStream ois = new ObjectInputStream(fis);
277 md5s = (HashMap<String,String>)ois.readObject();
282 md5s = new HashMap<String,String>();
283 getLog().warn("Cannot read timestamps from saved: " + e);
288 md5s = new HashMap<String,String>();
291 saved.createNewFile();
293 catch (IOException e)
295 getLog().warn("Cannot create saved for timestamps: " + e);
299 ClassLoader classLoader;
302 getLog().debug("Creating ClassLoader for project-dependencies...");
303 List<String> classpathFiles = project.getCompileClasspathElements();
305 classpathFiles.addAll(project.getTestClasspathElements());
306 URL[] urls = new URL[classpathFiles.size()];
307 for (int i = 0; i < classpathFiles.size(); ++i)
309 getLog().debug("Dependency: " + classpathFiles.get(i));
310 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
312 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
316 getLog().error("Error while creating ClassLoader!", e);
317 throw new MojoExecutionException(e.getMessage());
320 Properties properties = new Properties();
322 /** Try to read configuration from properties-file */
325 File file = new File(hibernateProperties);
328 getLog().info("Reading properties from file " + hibernateProperties + "...");
329 properties.load(new FileInputStream(file));
332 getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
334 catch (IOException e)
336 getLog().error("Error while reading properties!", e);
337 throw new MojoExecutionException(e.getMessage());
340 /** Overwrite values from propertie-file or set, if given */
341 if (driverClassName != null)
343 if (properties.containsKey(DRIVER_CLASS))
345 "Overwriting property " +
346 DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
347 " with the value " + driverClassName
350 getLog().debug("Using the value " + driverClassName);
351 properties.setProperty(DRIVER_CLASS, driverClassName);
355 if (properties.containsKey(URL))
357 "Overwriting property " +
358 URL + "=" + properties.getProperty(URL) +
359 " with the value " + url
362 getLog().debug("Using the value " + url);
363 properties.setProperty(URL, url);
365 if (username != null)
367 if (properties.containsKey(USERNAME))
369 "Overwriting property " +
370 USERNAME + "=" + properties.getProperty(USERNAME) +
371 " with the value " + username
374 getLog().debug("Using the value " + username);
375 properties.setProperty(USERNAME, username);
377 if (password != null)
379 if (properties.containsKey(PASSWORD))
381 "Overwriting property " +
382 PASSWORD + "=" + properties.getProperty(PASSWORD) +
383 " with the value " + password
386 getLog().debug("Using the value " + password);
387 properties.setProperty(PASSWORD, password);
389 if (hibernateDialect != null)
391 if (properties.containsKey(DIALECT))
393 "Overwriting property " +
394 DIALECT + "=" + properties.getProperty(DIALECT) +
395 " with the value " + hibernateDialect
398 getLog().debug("Using the value " + hibernateDialect);
399 properties.setProperty(DIALECT, hibernateDialect);
402 /** The generated SQL varies with the dialect! */
403 if (md5s.containsKey(DIALECT))
405 String dialect = properties.getProperty(DIALECT);
406 if (md5s.get(DIALECT).equals(dialect))
407 getLog().debug("SQL-dialect unchanged.");
410 getLog().debug("SQL-dialect changed: " + dialect);
412 md5s.put(DIALECT, dialect);
418 md5s.put(DIALECT, properties.getProperty(DIALECT));
421 if (md5s.containsKey(ENVERS))
423 String envers = properties.getProperty(ENVERS);
424 if (md5s.get(ENVERS).equals(envers))
425 getLog().debug("Envers unchanged.");
428 getLog().debug("Envers changed: " + envers);
430 md5s.put(ENVERS, envers.toString());
436 md5s.put(ENVERS, properties.getProperty(ENVERS));
439 if (envers != null) {
440 if (properties.containsKey(ENVERS))
442 "Overwriting property " +
443 ENVERS + "=" + properties.getProperty(ENVERS) +
444 " with the value " + envers
447 getLog().debug("Using the value " + envers);
448 properties.setProperty(ENVERS, envers.toString());
451 if (properties.isEmpty())
453 getLog().error("No properties set!");
454 throw new MojoFailureException("Hibernate-Configuration is missing!");
460 target = Target.valueOf(this.target.toUpperCase());
462 catch (IllegalArgumentException e)
464 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
465 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
466 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
471 type = Type.valueOf(this.type.toUpperCase());
473 catch (IllegalArgumentException e)
475 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
476 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
477 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
480 if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
482 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
486 && !target.equals(Target.SCRIPT)
487 && !target.equals(Target.NONE)
491 getLog().info("No modified annotated classes found and dialect unchanged.");
492 getLog().info("Skipping schema generation!");
493 project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
497 getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
498 for (Entry<Object,Object> entry : properties.entrySet())
499 getLog().info(" " + entry.getKey() + " = " + entry.getValue());
501 Connection connection = null;
505 * The connection must be established outside of hibernate, because
506 * hibernate does not use the context-classloader of the current
507 * thread and, hence, would not be able to resolve the driver-class!
518 Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
519 getLog().debug("Registering JDBC-driver " + driverClass.getName());
520 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
522 "Opening JDBC-connection to "
523 + properties.getProperty(URL)
525 + properties.getProperty(USERNAME)
527 + properties.getProperty(PASSWORD)
529 connection = DriverManager.getConnection(
530 properties.getProperty(URL),
531 properties.getProperty(USERNAME),
532 properties.getProperty(PASSWORD)
537 catch (ClassNotFoundException e)
539 getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
540 throw new MojoExecutionException(e.getMessage());
544 getLog().error("Cannot establish connection to database!");
545 Enumeration<Driver> drivers = DriverManager.getDrivers();
546 if (!drivers.hasMoreElements())
547 getLog().error("No drivers registered!");
548 while (drivers.hasMoreElements())
549 getLog().debug("Driver: " + drivers.nextElement());
550 throw new MojoExecutionException(e.getMessage());
553 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
554 MavenLogAppender.startPluginLog(this);
558 * Change class-loader of current thread, so that hibernate can
559 * see all dependencies!
561 Thread.currentThread().setContextClassLoader(classLoader);
563 Set<Class<?>> classes = scanForAnnotations(dir, classLoader, md5s);
565 Configuration config = new Configuration();
566 config.setProperties(properties);
567 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
568 for (Class<?> annotatedClass : classes)
570 getLog().debug("Class " + annotatedClass);
571 config.addAnnotatedClass(annotatedClass);
573 config.buildMappings();
574 if ("true".equals(properties.getProperty(ENVERS)))
576 getLog().debug("Using envers");
577 AuditConfiguration.getFor(config);
580 SchemaExport export = new SchemaExport(config, connection);
581 export.setOutputFile(outputFile);
582 export.setDelimiter(delimiter);
583 export.setFormat(format);
584 export.execute(target, type);
586 for (Object exception : export.getExceptions())
587 getLog().debug(exception.toString());
591 /** Stop Log-Capturing */
592 MavenLogAppender.endPluginLog(this);
594 /** Restore the old class-loader (TODO: is this really necessary?) */
595 Thread.currentThread().setContextClassLoader(contextClassLoader);
597 /** Close the connection */
600 if (connection != null)
603 catch (SQLException e)
605 getLog().error("Error while closing connection: " + e.getMessage());
609 /** Write md5-sums for annotated classes to file */
612 FileOutputStream fos = new FileOutputStream(saved);
613 ObjectOutputStream oos = new ObjectOutputStream(fos);
614 oos.writeObject(md5s);
620 getLog().error("Cannot write md5-sums to file: " + e);
625 * Needed, because DriverManager won't pick up drivers, that were not
626 * loaded by the system-classloader!
628 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
630 static final class DriverProxy implements Driver
632 private final Driver target;
634 DriverProxy(Driver target)
637 throw new NullPointerException();
638 this.target = target;
641 public java.sql.Driver getTarget()
647 public boolean acceptsURL(String url) throws SQLException
649 return target.acceptsURL(url);
653 public java.sql.Connection connect(
655 java.util.Properties info
660 return target.connect(url, info);
664 public int getMajorVersion()
666 return target.getMajorVersion();
670 public int getMinorVersion()
672 return target.getMinorVersion();
676 public DriverPropertyInfo[] getPropertyInfo(
683 return target.getPropertyInfo(url, info);
687 public boolean jdbcCompliant()
689 return target.jdbcCompliant();
693 * This Method cannot be annotated with @Override, becaus the plugin
694 * will not compile then under Java 1.6!
696 public Logger getParentLogger() throws SQLFeatureNotSupportedException
698 throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
702 public String toString()
704 return "Proxy: " + target;
708 public int hashCode()
710 return target.hashCode();
714 public boolean equals(Object obj)
716 if (!(obj instanceof DriverProxy))
718 DriverProxy other = (DriverProxy) obj;
719 return this.target.equals(other.target);
723 public Set<Class<?>> scanForAnnotations(File dir, ClassLoader classLoader, Map<String,String> md5s) throws MojoExecutionException, MojoFailureException {
724 Set<Class<?>> classes = new TreeSet<Class<?>>(
725 new Comparator<Class<?>>() {
727 public int compare(Class<?> a, Class<?> b) {
728 return a.getName().compareTo(b.getName());
734 AnnotationDB db = new AnnotationDB();
735 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
736 URL dirUrl = dir.toURI().toURL();
737 db.scanArchives(dirUrl);
738 if (scanTestClasses) {
739 dir = new File(testOutputDirectory);
741 throw new MojoExecutionException("Cannot scan for annotated test-classes in " + testOutputDirectory + ": directory does not exist!");
742 getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
743 dirUrl = dir.toURI().toURL();
744 db.scanArchives(dirUrl);
747 Set<String> classNames = new HashSet<String>();
748 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
749 classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
750 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
751 classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
752 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
753 classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
755 MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
756 for (String name : classNames) {
757 Class<?> annotatedClass = classLoader.loadClass(name);
758 classes.add(annotatedClass);
761 .getResourceAsStream(annotatedClass.getSimpleName() + ".class");
762 byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
764 while((i = is.read(buffer)) > -1)
765 digest.update(buffer, 0, i);
767 byte[] bytes = digest.digest();
768 BigInteger bi = new BigInteger(1, bytes);
769 String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
770 String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
771 if (!newMd5.equals(oldMd5))
773 getLog().debug("Found new or modified annotated class: " + name);
775 md5s.put(name, newMd5);
779 getLog().debug(oldMd5 + " -> class unchanged: " + name);
782 } catch (Exception e) {
783 getLog().error("Error while scanning!", e);
784 throw new MojoFailureException(e.getMessage());
787 if (classes.isEmpty())
788 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
790 getLog().debug("Detected classes with mapping-annotations:");
791 for (Class<?> annotatedClass : classes)
792 getLog().debug(" " + annotatedClass.getName());