0

I wanted to write one generic method for all different entities which returns List of messages .

Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'

For example : pseudo code

enter code here
private List<String> constraintViolationsDetected (genericentity) {
    Set<ConstraintViolation<?>> constraintViolations = validator.validate(?);
}

I am using javax.persistence[eclipselink-2.6.0] & Springs


Here is my code, I would like to Validate DeploymentConfiguration Entity before saving to database. I have 3 more different entities – I have to write validation for other entities also. Note: Finally I will call these methods and exposing as a Rest Services (Jersy)


1) DeploymentConfiguration is model/entity

package com.Demo.persistence.model;

import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

      public class DeploymentConfiguration implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name= DBConstants.DEPLOYMENT_ID,length = 255)
    @NotNull(message="DepoymentId type must be specified.")
    @Size(min=1, max=255)
    //@Valid
    private String depoymentId;

    @Basic
    @Column(name = DBConstants.SERVER_TYPE_VALUE, length = 255) 
    @NotNull(message="Deployment Server must be specified.")
    @Size(min=1, max=255)
    @Pattern(regexp="^(Dev|QA|Production)$",message="Invalid Servertype
private String deploymentServerValue;

     public String getDepoymentId () {
        return depoymentId;
    }

    public void setConnectionId(String depoymentId) {
        this.depoymentId = depoymentId;
    }

    public String getDeploymentServerValue () {
        return deploymentServerValue;
    }

    public void setDeploymentServerValue (String deploymentServerValue) 
{
        this.deploymentServerValue = deploymentServerValue;
}

2) DaoImplementation

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
public class DeploymentConfigurationDaoImpl 
{
EntityManagerProvider entityManagerProvider;
public void saveConnectionConfigurations(ConnectionConfiguration connConfig) {
        LOG.debug("Saving depoyment Configuration");
        if (null == connConfig) {
            return;
        }
        EntityManager em = null;
        em = getEntityManagerProvider().getEntityManager();
        try {
            em.getTransaction().begin();

                em.persist(connConfig);
                em.getTransaction().commit();
                em.getEntityManagerFactory().getCache().evictAll();
                LOG.debug("Persisting data");

        } 
catch (Exception ex) 
{
LOG.error("Error while persisting the depoyment Configuration", ex);

} finally {
    if (em != null && em.isOpen())
    em.close();

}

}

----------------Persistence .xml --------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="com.Demo.persistence" 
        transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>       
        <class>com.Demo.persistence.model.DeploymentConfiguration</class>
        <shared-cache-mode>ALL</shared-cache-mode>
        <properties>
            <property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
        </properties>
    </persistence-unit>
</persistence>

--------------------------------------------------------------------------------Test persistence.xml - Just sharing with you

enter code here

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="com.Demo.persistence"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>com.Demo.persistence.model.DeploymentConfiguration </class>

        <shared-cache-mode>ALL</shared-cache-mode>
        <properties>
            <!-- Connection Properties For Test DB -->
            <property name="javax.persistence.jdbc.url" value="jdbc:derby:memory:target/CoreServicesTestDB;create=true" />
            <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
            <property name="javax.persistence.jdbc.user" value="gomobile" />
            <property name="javax.persistence.jdbc.password" value="secret" />
            <property name="eclipselink.target-database" value="Derby" />
            <property name="eclipselink.target-server" value="None" />
            <!-- General Properties -->
            <property name="eclipselink.cache.shared.default" value="false" />
            <property name="eclipselink.weaving" value="static" />
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
            <property name="eclipselink.ddl-generation.output-mode"
                value="both" />
            <!-- Logging Properties -->
            <property name="eclipselink.logging.logger" value="DefaultLogger" />
            <property name="eclipselink.logging.level" value="FINEST" />
            <property name="eclipselink.logging.level.sql" value="FINEST" />
            <property name="eclipselink.logging.level.cache" value="FINEST" />
        </properties>
    </persistence-unit>
</persistence>

I am using below dependencies

<!-- JPA dependencies - Start -->
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
        </dependency>
        <!-- JPA dependencies - Start -->

        <!-- Spring dependencies - Start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <!-- Spring dependencies - End -->
        <!-- slf4j dependencies - Start -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>com.springsource.slf4j.log4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>com.springsource.slf4j.api</artifactId>
        </dependency>
        <!-- slf4j dependencies - End -->
        <!-- Junits dependencies - Start -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.orm</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.servicemix.bundles</groupId>
            <artifactId>org.apache.servicemix.bundles.derby</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Junits dependencies - End -->
Community
  • 1
  • 1
Showkath
  • 93
  • 1
  • 1
  • 7
  • Why? Why not just use `@Valid` on the method argument, why try to create your own hack? – M. Deinum May 15 '15 at 16:58
  • Could you share one complete example please , for different entities. I tried to use class> ,object ,....Set> is not working. I am newbie in JAVA, Springs, JPA ecipselink. – Showkath May 16 '15 at 09:58
  • What I'm trying to explain is that you don't need such a method. Bean Validation already does this. So you are basically making things to complex and are trying to work around the framework. When using Spring MVC just annotate a `@ModelAttribute` with `@Valid` and be done. There is also method argument validation but that will only work with Hibernate validation and not eclipse link. – M. Deinum May 16 '15 at 10:56
  • I have shared my code , could you explain me how to write validations using Annotations. Note : we should use eclipselink ,springframework in our demo project, We are not using Spring MVC, we need to exposed our methods as Services (Jersy) – Showkath May 18 '15 at 13:31
  • If you are using Spring you are trying very hard to work around it. How to use JSR-303 validation is explained in the reference guide. Simply register a `LocalValidatorFactoryBean`. How to combine it with JPA (although this is for hibernate it should work for eclipse link as it is plain JPA) is explained [here](http://stackoverflow.com/questions/2712345/jsr-303-dependency-injection-and-hibernate). – M. Deinum May 18 '15 at 18:26

0 Answers0