-->
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.  [ 5 posts ] 
Author Message
 Post subject: Embebbed objects not beeing validated
PostPosted: Sun Mar 25, 2012 5:52 pm 
Newbie

Joined: Sun Mar 25, 2012 5:43 pm
Posts: 4
Hello,
I have a problem with hibernate validator, the embbebed objects are not beeing validated, this is my code:

The embebed object
Code:
package es.tresw.db.embeddable;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import es.tresw.db.entities.Municipality;
import es.tresw.db.entities.Province;
import es.tresw.db.entities.Zone;

@Embeddable
public class Address
{
   @Size(max=255,message="{campo_demasiado_largo}")
   @Column(name="ADDRESS", length=255)
   public String address;
   
   @Size(max=255,message="{campo_demasiado_largo}")
   @Column(name="TYPE", length=255)
   public String type;
   
   @Size(min=5,max=5,message="{zipcode_incorrecto}")
   @Column(name="ZIP_CODE", length=255)
   public String zipCode;
   
   @NotNull(message="{campo_obligatorio}")
   @ManyToOne
   @JoinColumn(name = "ID_PROVINCE", nullable =false)
   public Province province;
   
   @NotNull(message="{campo_obligatorio}")
   @ManyToOne
   @JoinColumn(name = "ID_ZONE", nullable =false)
   public Zone zone;
   
   @NotNull(message="{campo_obligatorio}")
   @ManyToOne
   @JoinColumn(name = "ID_MUNICIPALITY", nullable =false)
   public Municipality municipality;
   
   
   public Address()
   {
      
   }
   
   public Address(String address, String type, Province province, Zone zone, Municipality municipality)
   {
      super();
      this.address = address;
      this.type = type;
      this.province = province;
      this.zone = zone;
      this.municipality=municipality;
   }

   public String getAddress()
   {
      return address;
   }
   
   public void setAddress(String address)
   {
      this.address = address;
   }
   
   public String getType()
   {
      return type;
   }
   
   public void setType(String type)
   {
      this.type = type;
   }
   
   public Province getProvince()
   {
      return province;
   }
   
   public void setProvince(Province province)
   {
      this.province = province;
   }
   
   public Zone getZone()
   {
      return zone;
   }

   public void setZone(Zone zone)
   {
      this.zone = zone;
   }

   public Municipality getMunicipality()
   {
      return municipality;
   }

   public void setMunicipality(Municipality municipality)
   {
      this.municipality = municipality;
   }

   public void setZipCode(String zipCode)
   {
      this.zipCode=zipCode;
   }
   
   public String getZipCode()
   {
      return zipCode;
   }
}


The object containing the embebed object:

Code:
package es.tresw.db.entities;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import es.tresw.db.embeddable.Address;
import es.tresw.db.embeddable.Appearance;
import es.tresw.db.embeddable.ContactInfo;

@Entity
@Table(name="SPORT_FACILITY",catalog="PISTEA")
public class SportFacility
{

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "ID", updatable = false, nullable = false)
   private Long id;
   
   @NotNull
   @Size(min=1,max=255,message="{campo_obligatorio}")
   @Pattern(regexp="[a-z]*",message="{identificador_incorrecto}")
   @Column(name="URL_NAME", length=255)
   private String urlName;
   
   @NotNull
   @Size(min=1,max=255,message="{campo_obligatorio}")
   @Column(name="NAME", length=255)
   private String name;
   
   @Column(name="GET_HERE", columnDefinition="TEXT")
   private String getHere;
   
   @Column(name="DESCRIPTION", columnDefinition="TEXT")
   private String description;
   
   @NotNull
   @Column(name="STATE", length=2)
   private Integer state;
   
   @Embedded
   @Valid
   private Address address;
   
   @Embedded
   @Valid
   private ContactInfo contactInfo;
   
   @Embedded
   private Appearance appearance;
   
   @OneToMany
   @JoinTable(name = "SPORT_FACILITY_FEATURES",
              joinColumns = { @JoinColumn(name = "SPORT_FACILITY_ID") },
             inverseJoinColumns = { @JoinColumn(name = "FEATURE_ID") })
   private Set<Feature> features=new HashSet<Feature>();
   
   @OneToMany   
   @JoinTable(name = "SPORT_FACIlITY_IMAGE",
              joinColumns = { @JoinColumn(name = "SPORT_FACILITY_ID") },
             inverseJoinColumns = { @JoinColumn(name = "IMAGE_ID") })
   private Set<Image> images=new HashSet<Image>();
   
   @OneToMany (mappedBy="sportFacility")
   private Set<Administrator> administrators=new HashSet<Administrator>();
   
   @OneToMany(mappedBy="sportFacility")   
   private Set<SportFacilityMember> members=new HashSet<SportFacilityMember>();
   
   @OneToMany(mappedBy="sportFacility")   
   private Set<Court> courts = new HashSet<Court>();

   @OneToMany
   @JoinTable(name = "SPORT_FACILITY_DAY",
              joinColumns = { @JoinColumn(name = "SPORT_FACILITY_ID") },
             inverseJoinColumns = { @JoinColumn(name = "DAY_ID") })
   private Set<Day> days = new HashSet<Day>();

   @OneToMany
   @JoinTable(name = "SPORT_FACILITY_SPECIAL_DAY",
              joinColumns = { @JoinColumn(name = "SPORT_FACILITY_ID") },
             inverseJoinColumns = { @JoinColumn(name = "DAY_ID") })
   private Set<SpecialDay> specialDays = new HashSet<SpecialDay>();
   
   public SportFacility()
   {
      
   }

   
   public SportFacility(String name, String getHere, String description, Integer state, Set<Feature> features, Set<Image> images, Set<Administrator> administrators, Address address, ContactInfo contactInfo, Appearance appearance, Set<SportFacilityMember> members, Set<Court> courts, Set<Day> days, Set<SpecialDay> specialDays)
   {
      this.name = name;
      this.getHere = getHere;
      this.description = description;
      this.state = state;
      this.features = features;
      this.images = images;
      this.administrators = administrators;
      this.address = address;
      this.contactInfo = contactInfo;
      this.appearance = appearance;
      this.members=members;
      this.courts=courts;
      this.days=days;
      this.specialDays=specialDays;
   }


   public Long getId()
   {
      return id;
   }

   public void setId(Long id)
   {
      this.id = id;
   }

   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }

   public String getGetHere()
   {
      return getHere;
   }

   public void setGetHere(String getHere)
   {
      this.getHere = getHere;
   }

   public String getDescription()
   {
      return description;
   }

   public void setDescription(String description)
   {
      this.description = description;
   }

   public Integer getState()
   {
      return state;
   }

   public void setState(Integer state)
   {
      this.state = state;
   }

   public Set<Feature> getFeatures()
   {
      return features;
   }

   public void setFeatures(Set<Feature> features)
   {
      this.features = features;
   }

   public Set<Image> getImagenes()
   {
      return images;
   }

   public void setImages(Set<Image> images)
   {
      this.images = images;
   }

   public Set<Administrator> getAdministrators()
   {
      return administrators;
   }

   public void setAdministrators(Set<Administrator> administrators)
   {
      this.administrators = administrators;
   }

   public Address getAddress()
   {
      return address;
   }

   public void setAddress(Address address)
   {
      this.address = address;
   }

   public ContactInfo getContactInfo()
   {
      return contactInfo;
   }

   public void setContactInfo(ContactInfo contactInfo)
   {
      this.contactInfo = contactInfo;
   }

   public Appearance getAppearance()
   {
      return appearance;
   }

   public void setAppearance(Appearance appearance)
   {
      this.appearance = appearance;
   }

   public Set<SportFacilityMember> getMembers() {
      return members;
   }


   public void setMembers(Set<SportFacilityMember> members)
   {
      this.members = members;
   }


   public String getUrlName()
   {
      return urlName;
   }


   public void setUrlName(String urlName)
   {
      this.urlName = urlName;
   }


   public Set<Image> getImages()
   {
      return images;
   }


   public Set<Court> getCourts()
   {
      return courts;
   }


   public void setCourts(Set<Court> courts)
   {
      this.courts = courts;
   }


   public Set<Day> getDays() {
      return days;
   }


   public void setDays(Set<Day> days) {
      this.days = days;
   }


   public Set<SpecialDay> getSpecialDays()
   {
      return specialDays;
   }


   public void setSpecialDays(Set<SpecialDay> specialDays)
   {
      this.specialDays = specialDays;
   }

}




The test case:

Code:
package es.tresw.db.dao;

import static org.junit.Assert.*;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import junit.framework.Assert;

import org.hibernate.validator.HibernateValidator;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import es.tresw.db.embeddable.Address;
import es.tresw.db.embeddable.Appearance;
import es.tresw.db.embeddable.ContactInfo;
import es.tresw.db.entities.Client;
import es.tresw.db.entities.Feature;
import es.tresw.db.entities.Image;
import es.tresw.db.entities.Municipality;
import es.tresw.db.entities.Province;
import es.tresw.db.entities.SportFacility;
import es.tresw.db.entities.SportFacilityMember;
import es.tresw.db.entities.Zone;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:intercambia-servlet-test.xml"})
@Transactional
public class TestSportFacilityDao{
   

   @Autowired
   private I_SportFacilityDao sportFacilityDao;
   @Autowired
   private I_ProvinceDao provinceDao;
   @Autowired
   private I_ClientDao clientDao;
   @Autowired
   private I_ImageDao imageDao;
   @Autowired
   private I_ZoneDao zoneDao;
   @Autowired
   LocalValidatorFactoryBean validator;
   
   
   @Test
   @Rollback(false)
   public void testCreateFail()
   {
      SportFacility sf = new SportFacility();
      Set<ConstraintViolation<SportFacility>> constraintViolations = validator.validate(sf);
      sf.setAddress(new Address());
      if(constraintViolations.size() > 0)
      {
         Iterator<ConstraintViolation<SportFacility>> iterator = constraintViolations.iterator();
         while(iterator.hasNext())
         {
            ConstraintViolation<SportFacility> cv = iterator.next();
            System.out.println(cv.getMessage());
            System.out.println(cv.getPropertyPath());
         }
         ConstraintViolation<SportFacility> cv = constraintViolations.iterator().next();
      }      
   }

   @Test
   @Rollback(false)
   public void testCreateSuccess()
   {
      SportFacility sf = new SportFacility();
      sf.setName("Name");
      sf.setUrlName("asdasdasdasd");
      sf.setState(1);
      ContactInfo ci = new ContactInfo();
      ci.setTelephone1("asdasdasd");
      ci.setEmail("asdad@asdsad.com" + new Date().getTime());
      sf.setContactInfo(ci);
      
      Address a = new Address();
      a.setAddress("asdasd sdas d");
      a.setZipCode("41013");
      
      Province p = provinceDao.read(new Long(1));
      a.setProvince(p);
      Municipality m = p.getMunicipalities().iterator().next();
      a.setMunicipality(m);
      Zone zone = new Zone();
      zone.setMunicipality(m);
      zone.setName("zona1");
      zoneDao.create(zone);
      a.setZone(zone);
      sf.setAddress(a);
      try
      {
         sportFacilityDao.create(sf);
      }
      catch (ConstraintViolationException e)
      {
         assertEquals(1, e.getConstraintViolations().size());
      }
   }

   
   @Test
   public void testUpdate()
   {
      SportFacility sportFacility = sportFacilityDao.readAll().get(0);
      List<Client> clients = clientDao.readAll();
      if(clients.size()>0)
      {
         SportFacilityMember sportFacilityMember = new SportFacilityMember();
         sportFacilityMember.setClient(clients.get(0));
         sportFacilityMember.setSportFacility(sportFacility);
         Set<SportFacilityMember> members = new HashSet<SportFacilityMember>();
         members.add(sportFacilityMember);
         sportFacility.setMembers(members);
      }
      sportFacilityDao.update(sportFacility);
      SportFacility sportFacilityUpdated = sportFacilityDao.read(sportFacility.getId());
      assertEquals(sportFacility.getMembers(), sportFacilityUpdated.getMembers());
   }
   
   
   @Test
   public void testReadAll()
   {
      assertTrue(sportFacilityDao.readAll().size()>0);
   }
   
   @Test
   public void testReadOne()
   {
      Long id = sportFacilityDao.readAll().get(0).getId();
      assertNotNull(sportFacilityDao.read(id));
   }
   
   @Test
   @Transactional
   public void testDelete()
   {
      SportFacility sportFacility = sportFacilityDao.readAll().get(0);
      Long id = sportFacility.getId();
      sportFacilityDao.delete(sportFacility);
      assertNull(sportFacilityDao.read(id));      
   }

   
   public void setSportFacility(I_SportFacilityDao sportFacilityDao)
   {
      this.sportFacilityDao=sportFacilityDao;
   }
   
   public void setProvinceDao(I_ProvinceDao provinceDao)
   {
      this.provinceDao=provinceDao;
   }

   public void setClientDao(I_ClientDao clientDao)
   {
      this.clientDao=clientDao;
   }
   
   public void setZoneDao(I_ZoneDao zoneDao)
   {
      this.zoneDao=zoneDao;
   }
   
   public void setValidator(LocalValidatorFactoryBean validator)
   {
      this.validator=validator;
   }
}




If you take a look on jUnit test case, when I print the constrain validations, it only prints the ones of the main object.

Thanks in advance.


Top
 Profile  
 
 Post subject: Re: Embebbed objects not beeing validated
PostPosted: Wed Mar 28, 2012 4:53 am 
Hibernate Team
Hibernate Team

Joined: Thu Apr 05, 2007 5:52 am
Posts: 1689
Location: Sweden
Hi,

that's a lot of code to look at ;-) and it is not so simple as just cut&paste to get this to run. So where exactly is your problem? Does validation work when you make the call explicitly (meaning getting a Validator instance and calling validate)? It should. I assume your problem is that automatic validation based on Hibernate life cycle events (like create, update) is not working. Of course I cannot be sure. Can you describe in more detail what the problem is. It might also help if you condense your code down to just the minimum to show your problem. Is it possible to trigger the "wrong" behavior without Spring?

--Hardy


Top
 Profile  
 
 Post subject: Re: Embebbed objects not beeing validated
PostPosted: Wed Mar 28, 2012 5:08 pm 
Newbie

Joined: Sun Mar 25, 2012 5:43 pm
Posts: 4
Hi,
Jejejejej yo are right. Ok, the problem basically is that if I do this:
Code:
      SportFacility sf = new SportFacility();
      Set<ConstraintViolation<SportFacility>> constraintViolations = validator.validate(sf);
      if(constraintViolations.size() > 0)
      {
         Iterator<ConstraintViolation<SportFacility>> iterator = constraintViolations.iterator();
         while(iterator.hasNext())
         {
            ConstraintViolation<SportFacility> cv = iterator.next();
            System.out.println(cv.getMessage());
            System.out.println(cv.getPropertyPath());
         }
      }     
   }


I only get the validation constrains of SportFacility and not the ones belonging to Address which is the embedded object.


I also tried

Code:
   try
      {
         sportFacilityDao.create(sf);
         sportFacilityDao.getSession().flush();
      }
      catch (ConstraintViolationException e) {
         Iterator<ConstraintViolation<?>> iterator = e.getConstraintViolations().iterator();
         while(iterator.hasNext())
            System.out.println(iterator.next().getMessage());
         // TODO: handle exception
      }


But I cannot catch ConstraintVIolationException.....basically I need to do my testcases and test that the constrainviolations are thrown...

Better now :-)


Top
 Profile  
 
 Post subject: Re: Embebbed objects not beeing validated
PostPosted: Wed Mar 28, 2012 7:44 pm 
Newbie

Joined: Sun Mar 25, 2012 5:43 pm
Posts: 4
Ok, after some struggling...My junit looks like this now...

Code:
      SportFacility sf = new SportFacility();
      Set<ConstraintViolation<SportFacility>> constraintViolations = validator.validate(sf);
      sf.setAddress(new Address());
      if(constraintViolations.size() > 0)
      {
         Iterator<ConstraintViolation<SportFacility>> iterator = constraintViolations.iterator();
         while(iterator.hasNext())
         {
            ConstraintViolation<SportFacility> cv = iterator.next();
            System.out.println(cv.getMessage());
            System.out.println(cv.getPropertyPath());
         }
      }
     try
     {
         sportFacilityDao.create(sf);
     }
      catch (org.springframework.dao.DataIntegrityViolationException  e)
     {
         Assert.assertTrue(true);
     }
     catch (ConstraintViolationException e) {
      Iterator<ConstraintViolation<?>> it = e.getConstraintViolations().iterator();
      while(it.hasNext())
      {   
          ConstraintViolation<?> cv = it.next();
         System.out.println(cv.getMessage());
         System.out.println(cv.getPropertyPath());
      }
     }



At this point I have two questions, first of all I do not get the constrains from the embedded object unless I set an empty address like this:

Code:
      sf.setAddress(new Address());


Is that the expected behaviour? Do I have to set explitly an empty address to get a constraint validation. Also I do not get the message, for some reason I get the {campo_obligatorio} which is the key.

The second question is why canĀ“t I get catch the ConstraintViolationException ? when I debug it does not enter the catch but on a normal run it does print on console the messages.....why??


Top
 Profile  
 
 Post subject: Re: Embebbed objects not beeing validated
PostPosted: Mon Apr 02, 2012 10:25 am 
Newbie

Joined: Mon Mar 26, 2012 4:57 am
Posts: 2
1.) As long as you don't set the @NotNull annotation on the Address property, a null value is valid.
Valid don't means, that the property must be not null!

2.) If you get the message key instead of the message, check your message interpolation setup. Maybe the validator don't know your message property files.


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