-->
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.  [ 10 posts ] 
Author Message
 Post subject: Hibernate validation
PostPosted: Sun Jul 03, 2011 6:04 am 
Newbie

Joined: Sun Jul 03, 2011 5:44 am
Posts: 5
Hello,
Please help me to fix some problems in my project. Now, i try to write a small project - Phonebook.
I have Contact entity
Code:
@Entity
@Table(name="Contacts")
public class Contact {
   @Id
   @SequenceGenerator(name="gen_contact",sequenceName="GEN_CONTACTS")
   @GeneratedValue(strategy=GenerationType.AUTO, generator = "gen_contact")   
   private int id;
   @Length(min=3,max=5, message="mai putin de 5")
   private String fname;
   private String lname;
   private String phonenumber;
   private String type_phone;
   @Temporal(TemporalType.DATE)
   private Date date_connect;

When i try to add a new contact, if i input a string fname in my input form with length=4, it's OK ... if a try to
input a string with length=7 for ex. I receive a error message:
Code:
org.hibernate.validator.InvalidStateException: validation failed for: com.melc.domain.Contact
   org.hibernate.validator.event.ValidateEventListener.validate(ValidateEventListener.java:148)
   org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:172)
   org.hibernate.action.EntityInsertAction.preInsert(EntityInsertAction.java:178)
   org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:72)
   org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
   org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
   org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
   org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
   org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
   org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
   org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
   org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
   com.melc.dao.ContactDAOImpl.insertContact(ContactDAOImpl.java:57)
   com.melc.actions.phoneAction.insertContact(phoneAction.java:52)
   sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
   java.lang.reflect.Method.invoke(Method.java:597)
   com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
   com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
   com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
   com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
   org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
   com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
   com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
   com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
   com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
   com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
   org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
   org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
   org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)



I'm developing my project following this example http://www.vaannila.com/struts-2/struts-2-tutorial/struts-2-hibernate-validation-tutorial-1.html
Thank you!


Top
 Profile  
 
 Post subject: Re: Hibernate validation
PostPosted: Sun Jul 03, 2011 5:18 pm 
Hibernate Team
Hibernate Team

Joined: Sat Jan 24, 2009 12:46 pm
Posts: 388
According to the stack trace a validation of the constraints of your Contact entity is performed upon persisting it. As you have a @Length constraint with a maximum length of 5 at the fname attribute, validation of a Contact object with a 7 character fname fails, resulting in the exception. So IMO everything is just working as expected.

Note, that the text you mentioned is a bit older. So be sure to use the current Hibernate Validator version, which is 4.2.0. HV 4.x is the reference implementation of JSR 303 ("Bean Validation") and as such integrated with JPA 2. You can learn more about the integration of Bean Validation and JPA 2 in this blog post which I wrote a while ago.

--Gunnar

_________________
Visit my blog at http://musingsofaprogrammingaddict.blogspot.com/


Top
 Profile  
 
 Post subject: Re: Hibernate validation
PostPosted: Mon Jul 04, 2011 4:13 am 
Newbie

Joined: Sun Jul 03, 2011 5:44 am
Posts: 5
Thank you Gunnar for reply and for your blog ...
about JPA2 & HV : nice article... but i have one question: what kind of libraries i need:
hibernate-validator-4.2.0.Final, hibernate-validator-annotation-processor-4.2.0.Final - HV
and for JPA2?

thank you !!!


Top
 Profile  
 
 Post subject: Re: Hibernate validation
PostPosted: Mon Jul 04, 2011 3:52 pm 
Hibernate Team
Hibernate Team

Joined: Sat Jan 24, 2009 12:46 pm
Posts: 388
To get started with HV you basically only need to add hibernate-validator-4.2.0.Final.jar, refer to the HV reference guide for more details. The annotation processor is a compiler plug-in which helps you in detecting misplaced constraint annotations and similar programming errors. You can find more information on the AP here.

Which JPA libraries you need depends on the JPA provider you use. In the GitHub project accompanying the blog post I created separate Maven profiles for Hibernate, EclipseLink and OpenJPA. The versions might be not totally up to date, though.

--Gunnar

_________________
Visit my blog at http://musingsofaprogrammingaddict.blogspot.com/


Top
 Profile  
 
 Post subject: Re: Hibernate validation
PostPosted: Tue Jul 05, 2011 8:10 am 
Newbie

Joined: Sun Jul 03, 2011 5:44 am
Posts: 5
Thank you for your reply ... your info it's very useful
Can I ask you only one question: the practice ... if it's possible, I want to show you what I doing
I have a function:
Code:
import java.util.Collection;
import java.util.HashSet;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;

public class ContactValidation {

   Collection errors = null;

   public Collection validate(Class clazz, Object obj) {

      InvalidValue[] invalidValues = null;
      try {
         errors = new HashSet();
         ClassValidator classValidator = new ClassValidator(clazz,loadproperties());
         invalidValues = classValidator.getInvalidValues(obj);
         System.err.println(" invalidValues " + invalidValues);
         for (int i = 0; i < invalidValues.length; i++) {

            errors.add(invalidValues[i].getMessage().trim());
            System.err.println(invalidValues[i].getMessage().trim());

         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      return errors;
   }

   public ResourceBundle loadproperties() {
      String baseName = "Contact.properties";
      // ebook.properties is properties file name
      ResourceBundle rb = null;
      try {
         // Get the resource bundle for the default locale
         rb = ResourceBundle.getBundle(baseName);
      } catch (MissingResourceException e) {
         // The resource bundle cannot be found or
         // the key does not exist in the resource bundle
      }
      return rb;
   }
}

witch get the errors into Collection object.
in Action class I have next code:
Code:
   public String insertContact(){
      ContactValidation c = new ContactValidation();
      Collection err = c.validate(Contact.class, contact);
      if(err.size()>0){
         this.setActionErrors(err);
         //return Action.ERROR;
      }
      contactDAO.insertContact(contact);
      return "SUCCESS";
   }

where Contact contact;

in final, I have the same error ... I'm already desperate with HV
thank you again.


Top
 Profile  
 
 Post subject: Re: Hibernate validation
PostPosted: Tue Jul 05, 2011 1:40 pm 
Hibernate Team
Hibernate Team

Joined: Sat Jan 24, 2009 12:46 pm
Posts: 388
I'm afraid I can't follow. What do you mean by "the same error"? What is the exact problem you're facing and what is the behavior you're expecting instead? Btw. according to your imports (o.h.v.ClassValidator, o.h.v.InvalidValue) you're still using HV 3.x instead of 4.x.

--Gunnar

_________________
Visit my blog at http://musingsofaprogrammingaddict.blogspot.com/


Top
 Profile  
 
 Post subject: Re: Hibernate validation
PostPosted: Wed Jul 06, 2011 3:23 am 
Newbie

Joined: Sun Jul 03, 2011 5:44 am
Posts: 5
Thank you !
True, a used HV 3.x ...
Now a added two libraries to my project hibernate-validator-4.2.0.Final.jar and hibernate-validator-annotation-processor-4.2.0.Final.jar.
Its OK, but a have another error message:
Code:
Multiple markers at this line
   - The type javax.validation.Payload cannot be resolved. It is indirectly referenced from
    required .class files
   - The type javax.validation.Payload cannot be resolved. It is indirectly referenced from
    required .class files

thank you!


Top
 Profile  
 
 Post subject: Re: Hibernate validation
PostPosted: Wed Jul 06, 2011 5:40 pm 
Hibernate Team
Hibernate Team

Joined: Sat Jan 24, 2009 12:46 pm
Posts: 388
You're missing the Bean Validation API JAR.

If you are not using Maven to build your project (which would pull in everything needed transitively when adding the dependency to hibernate-validator), you'll have to add everything from the lib/required folder of the download archive to your classpath. Besides validation-api-1.0.0.GA.jar that's slf4j-api-1.6.1.jar.

Depending on the requirements of your application you might want to add one or more modules from lib/optional, for instance slf4j-log4j12-1.6.1.jar and log4j-1.2.16.jar for logging purposes. Refer to the readme.txt file of the download for more details.

Note that you don't need the annotation processor JAR at runtime. You only would have to add it at compile time if you want to use the annotation processor for checking your constraint annotations.

--Gunnar

_________________
Visit my blog at http://musingsofaprogrammingaddict.blogspot.com/


Top
 Profile  
 
 Post subject: Re: Hibernate validation
PostPosted: Thu Jul 07, 2011 11:39 am 
Newbie

Joined: Sun Jul 03, 2011 5:44 am
Posts: 5
Thank you !!!
you're always right! Now it's work :)
thank you again :)


Top
 Profile  
 
 Post subject: Hibernate validation
PostPosted: Wed Aug 10, 2011 4:55 am 
Newbie

Joined: Wed Aug 10, 2011 4:45 am
Posts: 3
Hi...To perform a validation of these constraints, we use a Validator instance. Let's have a look at the CarTest class:

package com.mycompany;

import static org.junit.Assert.*;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.junit.BeforeClass;
import org.junit.Test;

public class CarTest {

private static Validator validator;

@BeforeClass
public static void setUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}

@Test
public void manufacturerIsNull() {
Car car = new Car(null, "DD-AB-123", 4);

Set<ConstraintViolation<Car>> constraintViolations =
validator.validate(car);

assertEquals(1, constraintViolations.size());
assertEquals("may not be null", constraintViolations.iterator().next().getMessage());
}

@Test
public void licensePlateTooShort() {
Car car = new Car("Morris", "D", 4);

Set<ConstraintViolation<Car>> constraintViolations =
validator.validate(car);

assertEquals(1, constraintViolations.size());
assertEquals("size must be between 2 and 14", constraintViolations.iterator().next().getMessage());
}

@Test
public void seatCountTooLow() {
Car car = new Car("Morris", "DD-AB-123", 1);

Set<ConstraintViolation<Car>> constraintViolations =
validator.validate(car);

assertEquals(1, constraintViolations.size());
assertEquals("must be greater than or equal to 2", constraintViolations.iterator().next().getMessage());
}

@Test
public void carIsValid() {
Car car = new Car("Morris", "DD-AB-123", 2);

Set<ConstraintViolation<Car>> constraintViolations =
validator.validate(car);

assertEquals(0, constraintViolations.size());
}
}
In the setUp() method we get a Validator instance from the ValidatorFactory. A Validator instance is thread-safe and may be reused multiple times. For this reason we store it as field of our test class. We can use the Validator now to validate the different car instances in the test methods.

_________________
Cegonsoft


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 10 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.