Generated schema now corresponds to hibernate validators set on the beans
[hibernate4-maven-plugin] / src / main / java / de / juplo / plugins / hibernate4 / ValidationConfiguration.java
1 package de.juplo.plugins.hibernate4;
2
3 import java.lang.reflect.Method;
4 import java.util.Collection;
5 import java.util.Properties;
6 import org.hibernate.cfg.Configuration;
7 import org.hibernate.dialect.Dialect;
8 import org.hibernate.metamodel.source.MappingException;
9
10
11 /**
12  * This integration is usually performed by BeanValidationIntegrator.
13  * Unfortunately, that integration will only be activated upon
14  * initialization of the ServiceRegistry, which initializes
15  * DatasourceConnectionProviderImpl, which looks up the datasource,
16  * which requires a JNDI context ...
17  * We therefore reimplement the relevant parts of BeanValidatorIntegrator.
18  * Since that must occur after secondPassCompile(), which is invoked by
19  * Configuration.generateSchemaCreationScript, which is invoked by
20  * SchemaExport, some fancy subclassing is needed to invoke the integration
21  * at the right time.
22  * @author Mark Robinson <mark@mrobinson.ca>
23  */
24 public class ValidationConfiguration extends Configuration
25 {
26   Class dialectClass;
27
28   public ValidationConfiguration(String dialectClass)
29       throws
30         ClassNotFoundException
31   {
32     this.dialectClass = Class.forName(dialectClass);
33   }
34
35   @Override
36   protected void secondPassCompile() throws MappingException
37   {
38     super.secondPassCompile();
39
40     try
41     {
42       /** Thank you, hibernate folks, for making this useful class package private ... */
43       Method applyDDL =
44           Class
45             .forName("org.hibernate.cfg.beanvalidation.TypeSafeActivator")
46             .getMethod(
47                 "applyRelationalConstraints",
48                 Collection.class,
49                 Properties.class,
50                 Dialect.class
51                 );
52       applyDDL.setAccessible(true);
53       applyDDL.invoke(
54           null,
55           classes.values(),
56           getProperties(),
57           dialectClass.newInstance()
58           );
59     }
60     catch (Exception e)
61     {
62       throw new RuntimeException(e);
63     }
64   }
65 }