Saturday, February 6, 2010

JSR 303 Bean Validation: Error "java.lang.NoSuchMethodError: javax.persistence.Persistence.getPersistenceUtil()Ljavax/persistence/PersistenceUtil;"

When we adopted the JSR 303 Bean Validation into our ADF/EJB project, we encountered the above error, so I posted on hibernate forums and was advised to implement my own custom class that implements TraversableResolver (Check the discussion here).
Here I will post a simple working implementation that works.
TODO:
1) Create a class that implements TraversableResolver like below:
package blogspot.soadev.validator;

import java.lang.annotation.ElementType;
import javax.validation.Path;
import javax.validation.TraversableResolver;

public class CustomTraversableResolver implements TraversableResolver {
   
    public boolean isReachable(Object traversableObject, Path.Node traversableProperty, 
                               Class rootBeanType, Path pathToTraversableObject, 
                               ElementType elementType) {
        return true;
    }

    public boolean isCascadable(Object object, Path.Node node, Class c,
                                Path path, ElementType elementType) {
        return true;
    }
}

2) Modify your code that gets the validator instance to as follows:
import blogspot.soadev.validator.CustomTraversableResolver;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
...

ValidatorFactory factory = Validation.byDefaultProvider().configure()
                      .traversableResolver( new CustomTraversableResolver() )
                      .buildValidatorFactory();
Validator validator = factory.getValidator();

Kudos to Java Powers who first attended and tested this!

Related Posts

Cheers!

Pino

EJB with EclipseLink: How to ensure that your query returns fresh data

If you wanted to retrieve always fresh data from your query, you could set the hints parameter in the @NamedQuery declaration like below:
...
import org.eclipse.persistence.config.HintValues;
import org.eclipse.persistence.config.QueryHints;
...

@NamedQuery(name = "findEmployeesByDepartmentId", 
            query = "select o from Employee o where o.department.id = :departmentId"), 
            hints = {@QueryHint(name=QueryHints.REFRESH, value=HintValues.TRUE)}

It could also be set programmatically thru the setHints() method of the Query API. An example would be:
public List findEmployeesByDepartmentId(Long departmentId){
     Query query = em.createNamedQuery("findEmployeesByDepartmentId");
     query.setParameter("departmentId", departmentId);
     query.setHint(QueryHints.REFRESH, HintValues.TRUE);
     return query.getResultList();
  }