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;
21 import java.io.FileInputStream;
22 import java.io.IOException;
24 import java.net.URLClassLoader;
25 import java.sql.Connection;
26 import java.sql.Driver;
27 import java.sql.DriverManager;
28 import java.sql.DriverPropertyInfo;
29 import java.sql.SQLException;
30 import java.util.Enumeration;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Properties;
36 import javax.persistence.Embeddable;
37 import javax.persistence.Entity;
38 import javax.persistence.MappedSuperclass;
39 import org.apache.maven.plugin.AbstractMojo;
40 import org.apache.maven.plugin.MojoExecutionException;
41 import org.apache.maven.plugin.MojoFailureException;
42 import org.apache.maven.project.MavenProject;
43 import org.hibernate.cfg.Configuration;
44 import org.hibernate.tool.hbm2ddl.SchemaExport;
45 import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
46 import org.hibernate.tool.hbm2ddl.Target;
47 import org.scannotation.AnnotationDB;
51 * Goal which extracts the hibernate-mapping-configuration and
52 * exports an according SQL-database-schema.
55 * @phase process-classes
57 * @requiresDependencyResolution runtime
59 public class Hbm2DdlMojo extends AbstractMojo
62 * The project whose project files to create.
64 * @parameter expression="${project}"
68 private MavenProject project;
71 * Directories to scan.
73 * @parameter expression="${project.build.outputDirectory}"
75 private String outputDirectory;
80 * @parameter expression="${maven.test.skip}"
87 * @parameter expression="${hibernate.connection.driver_class}
89 private String driverClassName;
94 * @parameter expression="${hibernate.connection.url}"
101 * @parameter expression="${hibernate.connection.username}"
103 private String username;
108 * @parameter expression="${hibernate.connection.password}"
110 private String password;
115 * @parameter expression="${hibernate.dialect}"
117 private String hibernateDialect;
120 * Hibernate configuration file.
122 * @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
124 private String hibernateProperties;
127 * Target of execution:
129 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
130 * <li><strong>EXPORT</strong> create database <strong>(DEFAULT!)</strong></li>
131 * <li><strong>SCRIPT</strong> export schema to SQL-script</li>
132 * <li><strong>BOTH</strong></li>
134 * @parameter default-value="EXPORT"
136 private String target;
141 * <li><strong>NONE</strong> do nothing - just validate the configuration</li>
142 * <li><strong>CREATE</strong> create database-schema</li>
143 * <li><strong>DROP</strong> drop database-schema</li>
144 * <li><strong>BOTH</strong> <strong>(DEFAULT!)</strong></li>
146 * @parameter default-value="BOTH"
153 * @parameter default-value="${project.build.outputDirectory}/schema.sql"
155 private String outputFile;
158 * Delimiter in output-file.
160 * @parameter default-value=";"
162 private String delimiter;
165 * Format output-file.
167 * @parameter default-value="true"
169 private boolean format;
173 public void execute()
175 MojoFailureException,
176 MojoExecutionException
181 File dir = new File(outputDirectory);
183 throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
186 Set<String> classes = new HashSet<String>();
189 AnnotationDB db = new AnnotationDB();
190 getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
191 URL dirUrl = dir.toURI().toURL();
192 db.scanArchives(dirUrl);
193 if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
194 classes.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
195 if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
196 classes.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
197 if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
198 classes.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
200 catch (IOException e)
202 getLog().error("Error while scanning!", e);
203 throw new MojoFailureException(e.getMessage());
205 if (classes.isEmpty())
206 throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
208 Properties properties = new Properties();
210 /** Try to read configuration from properties-file */
213 File file = new File(hibernateProperties);
216 getLog().info("Reading properties from file " + hibernateProperties + "...");
217 properties.load(new FileInputStream(file));
220 getLog().info("Ignoring nonexistent properties-file " + hibernateProperties + "!");
222 catch (IOException e)
224 getLog().error("Error while reading properties!", e);
225 throw new MojoExecutionException(e.getMessage());
228 /** Overwrite values from propertie-file or set if given */
229 if (driverClassName != null)
230 properties.setProperty("hibernate.connection.driver_class", driverClassName);
232 properties.setProperty("hibernate.connection.url", url);
233 if (username != null)
234 properties.setProperty("hibernate.connection.username", username);
235 if (password != null)
236 properties.setProperty("hibernate.connection.password", password);
237 if (hibernateDialect != null)
238 properties.setProperty("hibernate.dialect", hibernateDialect);
240 if (properties.isEmpty())
241 getLog().warn("No properties set!");
242 for (Entry<Object,Object> entry : properties.entrySet())
243 getLog().debug(entry.getKey() + " = " + entry.getValue());
245 ClassLoader classLoader = null;
248 getLog().debug("Creating ClassLoader for project-dependencies...");
249 List<String> classpathFiles = project.getCompileClasspathElements();
250 URL[] urls = new URL[classpathFiles.size()];
251 for (int i = 0; i < classpathFiles.size(); ++i)
253 getLog().debug("Dependency: " + classpathFiles.get(i));
254 urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
256 classLoader = new URLClassLoader(urls, getClass().getClassLoader());
260 getLog().error("Error while creating ClassLoader!", e);
261 throw new MojoExecutionException(e.getMessage());
264 Configuration config = new Configuration();
265 config.setProperties(properties);
268 getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
269 for (String annotatedClass : classes)
271 getLog().debug("Class " + annotatedClass);
272 config.addAnnotatedClass(classLoader.loadClass(annotatedClass));
275 catch (ClassNotFoundException e)
277 getLog().error("Error while adding annotated classes!", e);
278 throw new MojoExecutionException(e.getMessage());
281 Target target = null;
284 target = Target.valueOf(this.target);
286 catch (IllegalArgumentException e)
288 getLog().error("Invalid value for configuration-option \"target\": " + this.target);
289 getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
290 throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
295 type = Type.valueOf(this.type);
297 catch (IllegalArgumentException e)
299 getLog().error("Invalid value for configuration-option \"type\": " + this.type);
300 getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
301 throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
304 Connection connection = null;
308 * The connection must be established outside of hibernate, because
309 * hibernate does not use the context-classloader of the current
310 * thread and, hence, would not be able to resolve the driver-class!
321 Class driverClass = classLoader.loadClass(driverClassName);
322 getLog().debug("Registering JDBC-driver " + driverClass.getName());
323 DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
324 getLog().debug("Opening JDBC-connection to " + url + " as " + username + " with password " + password);
325 connection = DriverManager.getConnection(url, username, password);
329 catch (ClassNotFoundException e)
331 getLog().error("Dependency for driver-class " + driverClassName + " is missing!");
332 throw new MojoExecutionException(e.getMessage());
336 getLog().error("Cannot establish connection to database!");
337 Enumeration<Driver> drivers = DriverManager.getDrivers();
338 if (!drivers.hasMoreElements())
339 getLog().error("No drivers registered!");
340 while (drivers.hasMoreElements())
341 getLog().debug("Driver: " + drivers.nextElement());
342 throw new MojoExecutionException(e.getMessage());
345 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
346 MavenLogAppender.startPluginLog(this);
350 * Change class-loader of current thread, so that hibernate can
351 * see all dependencies!
353 Thread.currentThread().setContextClassLoader(classLoader);
355 SchemaExport export = new SchemaExport(config, connection);
356 export.setOutputFile(outputFile);
357 export.setDelimiter(delimiter);
358 export.setFormat(format);
359 export.execute(target, type);
361 for (Object exception : export.getExceptions())
362 getLog().debug(exception.toString());
366 /** Stop Log-Capturing */
367 MavenLogAppender.endPluginLog(this);
369 /** Restore the old class-loader (TODO: is this really necessary?) */
370 Thread.currentThread().setContextClassLoader(contextClassLoader);
372 /** Close the connection */
377 catch (SQLException e)
379 getLog().error("Error while closing connection: " + e.getMessage());
385 * Needed, because DriverManager won't pick up drivers, that were not
386 * loaded by the system-classloader!
388 * http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location
390 static final class DriverProxy implements Driver
392 private final Driver target;
394 DriverProxy(Driver target)
397 throw new NullPointerException();
398 this.target = target;
401 public java.sql.Driver getTarget()
407 public boolean acceptsURL(String url) throws SQLException
409 return target.acceptsURL(url);
413 public java.sql.Connection connect(
415 java.util.Properties info
420 return target.connect(url, info);
424 public int getMajorVersion()
426 return target.getMajorVersion();
430 public int getMinorVersion()
432 return target.getMinorVersion();
436 public DriverPropertyInfo[] getPropertyInfo(
443 return target.getPropertyInfo(url, info);
447 public boolean jdbcCompliant()
449 return target.jdbcCompliant();
453 public String toString()
455 return "Proxy: " + target;
459 public int hashCode()
461 return target.hashCode();
465 public boolean equals(Object obj)
467 if (!(obj instanceof DriverProxy))
469 DriverProxy other = (DriverProxy) obj;
470 return this.target.equals(other.target);