2 Replies Latest reply on Sep 2, 2010 3:57 PM by kbrender

    Dynamically bypass Hibernate Validation by overriding ValidateEventListener

    kbrender

      I want to temporarily bypass the Hibernate Validator to persist an object which fails Hibernate's validation. I believe that an acceptable solution is to extend the Hibernate class ValidateEventListener. My custom listener shall have two static methods disable and reEnable. These methods shall toggle the boolean value of a Java ThreadLocal inside the custom listener. This shall enable me to bypass Hibernate validation in the following manner.


      void myMethod() {
          CustomValidateEventListener.disable();  // Disable Hibernate validation
          entityManager.flush();                  // Flush an update
          CustomValidateEventListener.reEnable(); // Re-enable Hibernate validation
      }



      In Hibernate, I must set the CustomValidateEventListener as the default listener, in lieu of the ValidateEventListener, inside hibernate.cfg.xml; but my application's configuration of Seam does not have this file. How can I change the default validation event listener in Seam? Is there a better solution?

        • 1. Re: Dynamically bypass Hibernate Validation by overriding ValidateEventListener
          njrich28

          Can you set it in persistence.xml instead?

          • 2. Re: Dynamically bypass Hibernate Validation by overriding ValidateEventListener
            kbrender
            Yes. I think I have figured it out. First, I deactivate automatic registration of the default validation listener (Hibernate's ValidateEventListener). Second, I register the custom listener as "pre-insert" and "pre-update". In persistence.xml, these changes appear as follow:

            <property name="hibernate.validator.autoregister_listeners" value="false" />
            <property name="hibernate.ejb.event.pre-insert" value="org.mypackage.CustomValidateEventListener" />
            <property name="hibernate.ejb.event.pre-update" value="org.mypackage.CustomValidateEventListener" />

            Thanks for the suggestion! Putting the configuration in persistence.xml seems to work for me, although this configuration is not as ideal as something like "<property name="defaultValidateListener" value="..." />". I derived this solution from the Hibernate documentation on event listeners (http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/configuration.html) and from this blog which discusses the same problem:

            http://www.nearinfinity.com/blogs/page/sleberkn?entry=validating_domain_objects_in_hibernate4

            (Sorry for the font. The formatting options are difficult to use.)