-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 8 posts ] 
Author Message
 Post subject: SchemaExport misses javax.validation.constraints.*
PostPosted: Fri Feb 24, 2012 6:27 pm 
Newbie

Joined: Fri Feb 24, 2012 6:03 pm
Posts: 1
Hi,

When I generate a DDL when connecting to a database (configured with a session factory) and set generateDdl to "true", the database is configured correctly.
Hibernate finds the javax.validation.constraints annotations (e.g.: @Size) and uses them to set the sizes and other constraints of fields.
Wonderful!


However, if I choose to generate a DDL programatically, those annotations are ignored. The DDL comes out allright,
but only sizes found in @Column are picked up. Those in @Size are ignored.

I have tried something like this:
...
hibernateConfiguration = new Configuration();
hibernateConfiguration.buildSettings(new BootstrapServiceRegistryBuilder().build());
hibernateConfiguration.setProperty("hibernate.hbm2ddl.auto", "update");
hibernateConfiguration.setProperty("hibernate.dialect", dialectClassName);
hibernateConfiguration.setProperty("hibernate.validator.apply_to_ddl", "true");
hibernateConfiguration.setProperty("javax.persistence.validation.mode", "AUTO")
for (Class<?> entityClass : entityClassCollection) {
hibernateConfiguration.addAnnotatedClass(entityClass);
}
SchemaExport schemaExport = new SchemaExport(hibernateConfiguration);
schemaExport.setDelimiter(";");
schemaExport.execute(true, false, false, false);
...
Tracing and debugging the Hibernate sources, I found that somehow class BeanValidationIntegrator should be used. It is used when running the web application.
But when using SchemaExporter, class BeanValidationIntegrator never is used.

Am I missing something?
In both cases Hibernate Validator and JSR303 jar dependencies are present.
Should I set some other configuration key?
What can be done?

The above was done with hibernate-core version 4.1.0.Final (which contains the SchemaExport class).

Kind regards,

Gerard


Top
 Profile  
 
 Post subject: Re: SchemaExport misses javax.validation.constraints.*
PostPosted: Wed Apr 25, 2012 2:00 am 
Newbie

Joined: Thu Apr 01, 2010 5:52 am
Posts: 2
hi,
Did you find solution for this >


Top
 Profile  
 
 Post subject: Re: SchemaExport misses javax.validation.constraints.*
PostPosted: Tue May 22, 2012 3:24 am 
Newbie

Joined: Tue May 20, 2008 12:21 pm
Posts: 4
Hi, did you find a solution? We are facing the same issue.


Top
 Profile  
 
 Post subject: Re: SchemaExport misses javax.validation.constraints.*
PostPosted: Fri Jun 01, 2012 9:07 am 
Newbie

Joined: Tue Aug 23, 2011 7:46 am
Posts: 3
When this issue will be solved?


Top
 Profile  
 
 Post subject: Re: SchemaExport misses javax.validation.constraints.*
PostPosted: Fri Jun 01, 2012 11:42 am 
Beginner
Beginner

Joined: Wed Nov 21, 2007 8:04 am
Posts: 27
You may find the following hack useful:

Code:
/**
* Uses the JPA configuration to emit the schema creation script.
*/
/*
* The deprecation can not be avoided, as it appears that Ejb3Configuration was
* deprecated before its substitute has been implemented (the JIRA issues
* referenced by the deprecation notice have been rescheduled for Hibernate 5).
* Also, as of hibernate 4.1.2, hibernate still uses Ejb3Configuration to create
* an EntityManagerFactory.
*/
@SuppressWarnings("deprecation")
public class ExportSchema {

    private static final String persistenceUnitName = "main";
   
    public static final String outputFileName = "target/populate_schema.sql";
   
    /**
     * @param dialectClass the dialect to be used by the sql script
     */
    public static void export(Class<? extends Dialect> dialectClass) {
        new File(outputFileName).getParentFile().mkdirs();

        Ejb3Configuration cfg = new Ejb3Configuration();
        if (beanValidationInClasspath()) {
            injectBeanValidationConstraintToDdlTranslator(cfg, dialectClass);
        }
        cfg.configure(persistenceUnitName, null);
        cfg.setProperty("hibernate.dialect", dialectClass.getName());
       
        SchemaExport exporter = new SchemaExport(cfg.getHibernateConfiguration());
        exporter.setFormat(true);
        exporter.setDelimiter(";");
        exporter.setOutputFile(outputFileName);

        exporter.execute(true, false, false, true);
    }
   
    private static boolean beanValidationInClasspath() {
        try {
            Class.forName("javax.validation.constraints.NotNull");
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
   
    // This integration is usually performed by BeanValidationIntegrator.
    // Unfortunately, that integration will only be activated upon
    // initialization of the ServiceRegistry, which initializes
    // DatasourceConnectionProviderImpl, which looks up the datasource,
    // which requires a JNDI context ...
    // We therefore reimplement the relevant parts of BeanValidatorIntegrator.
    // Since that must occur after secondPassCompile(), which is invoked by
    // Configuration.generateSchemaCreationScript, which is invoked by
    // SchemaExport, some fancy subclassing is needed to invoke the integration
    // at the right time.
   
    private static void injectBeanValidationConstraintToDdlTranslator(Ejb3Configuration jpaCfg, final Class<? extends Dialect> dialectClass) {
        try {
            Field cfgField = Ejb3Configuration.class.getDeclaredField("cfg");
            cfgField.setAccessible(true);
            cfgField.set(jpaCfg, new Configuration() {
                @Override
                protected void secondPassCompile() throws MappingException {
                    super.secondPassCompile();
                   
                    try {
                        // thank you, hibernate folks, for making this useful class package private ...
                        Method applyDDL = Class.forName("org.hibernate.cfg.beanvalidation.TypeSafeActivator") //
                                .getMethod("applyDDL", Collection.class, Properties.class, Dialect.class);
                        applyDDL.setAccessible(true);
                        applyDDL.invoke(null, classes.values(), getProperties(), dialectClass.newInstance());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                   
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


It causes bean validation constraints to be propagated to DDL when using hibernate-core-4.1.4.Final. A database connection is not required.


Top
 Profile  
 
 Post subject: Re: SchemaExport misses javax.validation.constraints.*
PostPosted: Mon Jun 04, 2012 4:22 am 
Newbie

Joined: Tue Aug 23, 2011 7:46 am
Posts: 3
Do you know how to do the same using Hibernate Session?


Top
 Profile  
 
 Post subject: Re: SchemaExport misses javax.validation.constraints.*
PostPosted: Mon Jun 04, 2012 7:08 am 
Beginner
Beginner

Joined: Wed Nov 21, 2007 8:04 am
Posts: 27
I assume it would be quite straightforward to adapt the above code. Since I only need what I posted above I won't be porting it into your environment.


Top
 Profile  
 
 Post subject: Re: SchemaExport misses javax.validation.constraints.*
PostPosted: Wed Dec 05, 2012 11:19 am 
Newbie

Joined: Wed Dec 05, 2012 10:35 am
Posts: 1
Thanks to Adrian for solution hint. But now generated schema (both Hibernate 4.1.4.Final and 4.1.5.Final) for Oracle10gDialect is empty. Patched Method is invoked but classes map is empty? Am I missing something?

Without Adrians Hack Hibernate 3.5.6 all columns are correctly defined, Entity:
Code:
    @NotNull(message = "{comment_notNull}")
    @Size(max = 1000, message = "{comment_max}")
    @Column(nullable = false)
    public String getComment() {
        return comment;
    }


Hibernate 3 generated:
Code:
comment varchar2(1000 char) not null

Hibernate 4 generated:
Code:
comment varchar2(255 char) not null

While defining comment property with length attribute
Code:
@Columns(length=1000)
results in
Code:
comment long not null


EDIT:
solved, my mistake was: i called EJB3Configuration.configure before, setting patched class.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 8 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.