Requirement Constraints

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Friday, 31 August 2012

Hibernate Validator - Creating custom constraints @Required – Example 4

Posted on 23:56 by Unknown

In this post, we will see how we can create our own custom constraints tailored to our specific requirements.

Creating our own custom constraint is not that much complicated, it is a matter of defining two steps :
a) Create a constraint annotation
b) Create a constraint validation

I am going to explain step by step for creating our own constraint  called @Required which is the combined of @NotNull and @NotEmpty.

Now let us start.

Environment


  1. Eclipse 3.7 Indigo IDE
  2. Hibernate 4.1.1
  3. JavaSE 1.6
  4. MySQL 5.1

Step 1:
Let us set up the environment first. Follow this post to set up Hibernate with java in eclipse IDE.

Step 2:
We need to add some more jar files for Validator. Please follow the steps

  1. Right click on Project and Select Properties.
  2. Select Java Build Path.
  3. Click “Add External JARs..” and include the following jar files. (you can also download by clicking the following files)

hibernate-validator-4.0.2.GA.jar
hibernate-validator-annotation-processor-4.1.0.Final.jar
slf4j-simple-1.4.2.jar
log4j-1.2.15.jar
slf4j-api-1.4.2.jar
validation-api-1.0.0.GA.jar

Step 3
In the mysql, create the following table.


 

CREATE TABLE `validatorexample5` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `firstName` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=latin1

Step 4
Now let us create the java bean without our constraint. Later we will come back , add our newly created custom constraint.

package domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import myConstraints.Required;


@Entity
@Table(name = "validatorexample5")
public class validatorexample5 {

@Id
@GeneratedValue
@Column(name = "ID")
private int ID;

@Column(name = "FirstName")
private String firstName;

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

}



 


Now let us map this class in the hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Mapping Classes -->
<mapping class="domain.validatorexample5" />

</session-factory>
</hibernate-configuration>

Very Important, We need add one more property in the above xml file as follows
<property name="javax.persistence.validation.mode">none</property>





Now let us create our constraint annotation as follows.


Now we can define the actual constraint annotation. If you've never designed an annotation before, this may look a bit scary, but actually it's not that hard: It is a matter of writing some boiler plate code and filling in the blanks.




package myConstraints;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = RequiredValidator.class)
@Documented
public @interface Required {

String message() default "{default message}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};



}

Next, we need to implement a constraint validator, that's able to validate elements with a @RequiredValidator. To do so, we implement the interface ConstraintValidator as shown below:




package myConstraints;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class RequiredValidator implements ConstraintValidator<Required, String> {

public void initialize(Required constraintAnnotation) {

}

public boolean isValid(String value, ConstraintValidatorContext constraintContext) {
if (value == null) {
return false;
}
if (value instanceof String) {
String stringValue = (String) value;
if (stringValue.trim().length() == 0) {
return false;
}
}
return true;
}

}



Now, let us go back to bean and add our custom constraint as follows.


package domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import myConstraints.Required;


@Entity
@Table(name = "validatorexample5")
public class validatorexample5 {

@Id
@GeneratedValue
@Column(name = "ID")
private int ID;

@Column(name = "FirstName")
@Required(message="First name cannot be empty or null")
private String firstName;

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

}


Now, in order to test our code, we will create our test class as follows


package test;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.Session;
import HibernateUtilities.HibernateUtil;
import domain.validatorexample5;

public class Test {
public static void main(String[] args) {


validatorexample5 v1 = new validatorexample5();


ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<validatorexample5>> constraintViolations = validator
.validate(v1);

// printing the results
for (ConstraintViolation<validatorexample5> constraintViolation : constraintViolations) {
System.out.println(constraintViolation.getPropertyPath() + " -> "
+ constraintViolation.getMessage());
}
Session session = HibernateUtil.beginTransaction();
session.save(v1);
HibernateUtil.CommitTransaction();

}
}


Now right click test.java and select run as Java Application. You can see the following output and shows the validation constraints.

2 [main] INFO org.hibernate.validator.util.Version - Hibernate Validator 4.0.2.GA
12 [main] INFO org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
firstName -> First name cannot be empty or null
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into validatorexample5 (FirstName) values (?)



 

That’s all


Project Structure:
image

Read More
Posted in | No comments

Thursday, 30 August 2012

Hibernate Validator - Creating custom constraints–Example

Posted on 10:56 by Unknown

In this post, we will see how we can create our own custom constraints tailored to our specific requirements.

Creating our own custom constraint is not that much complicated, it is a matter of defining two steps :
a) Create a constraint annotation
b) Create a constraint validation

I am going to explain step by step for creating our own constraint by taking hibernate documentation example as here..
Now let us start.

Environment


  1. Eclipse 3.7 Indigo IDE
  2. Hibernate 4.1.1
  3. JavaSE 1.6
  4. MySQL 5.1

Step 1:
Let us set up the environment first. Follow this post to set up Hibernate with java in eclipse IDE.

Step 2:
We need to add some more jar files for Validator. Please follow the steps

  1. Right click on Project and Select Properties.
  2. Select Java Build Path.
  3. Click “Add External JARs..” and include the following jar files. (you can also download by clicking the following files)

hibernate-validator-4.0.2.GA.jar
hibernate-validator-annotation-processor-4.1.0.Final.jar
slf4j-simple-1.4.2.jar
log4j-1.2.15.jar
slf4j-api-1.4.2.jar
validation-api-1.0.0.GA.jar

Step 3
In the mysql, create the following table.


CREATE TABLE `validatorexample4` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `firstName` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=latin1

Step 4
Now let us create the java bean without our constraint. Later we will come back , add our newly created custom constraint.

 

package domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "validatorexample4")
public class validatorexample4 {

@Id
@GeneratedValue
@Column(name = "ID")
private int ID;

@Column(name = "FirstName")
private String firstName;

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

}




Now let us map this class in the hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Mapping Classes -->
<mapping class="domain.validatorexample4" />

</session-factory>
</hibernate-configuration>

Very Important, We need add one more property in the above xml file as follows
<property name="javax.persistence.validation.mode">none</property>




 

Now let us create our constraint annotation as follows.


First we need a way to express the two case modes. We might use String constants, but a better way to go is to use a Java 5 enum for that purpose:

package myConstraints;

public enum CaseMode {
UPPER, LOWER;
}


Now we can define the actual constraint annotation. If you've never designed an annotation before, this may look a bit scary, but actually it's not that hard: It is a matter of writing some boiler plate code and filling in the blanks.




package myConstraints;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckCaseValidator.class)
@Documented
public @interface CheckCase {

String message() default "{default message}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

CaseMode value();

}




  • The annotation interface has three mandatory attributes: message, groups and payload

  • @Target({ METHOD, FIELD, ANNOTATION_TYPE }): Says, that methods, fields and annotation declarations may be annotated with @CheckCase (but not type declarations e.g.)

  • @Retention(RUNTIME): Specifies, that annotations of this type will be available at runtime by the means of reflection

  • @Constraint(validatedBy = CheckCaseValidator.class): Specifies the validator to be used to validate elements annotated with @CheckCase

  • @Documented: Says, that the use of @CheckCase will be contained in the JavaDoc of elements annotated with i

Next, we need to implement a constraint validator, that's able to validate elements with a @CheckCaseannotation. To do so, we implement the interface ConstraintValidator as shown below:



package myConstraints;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {

private CaseMode caseMode;

public void initialize(CheckCase constraintAnnotation) {
this.caseMode = constraintAnnotation.value();
}

public boolean isValid(String object, ConstraintValidatorContext constraintContext) {

if (object == null)
return true;

boolean isValid;
if (caseMode == CaseMode.UPPER) {
isValid = object.equals(object.toUpperCase());
}
else {
isValid = object.equals(object.toLowerCase());
}

return isValid;
}

}


The ConstraintValidator interface defines two type parameters, which we set in our implementation. The first one specifies the annotation type to be validated (in our example CheckCase), the second one the type of elements, which the validator can handle (here String).


In case a constraint annotation is allowed at elements of different types, a ConstraintValidator for each allowed type has to be implemented and registered at the constraint annotation as shown above.


The implementation of the validator is straightforward. The initialize() method gives us access to the attribute values of the annotation to be validated. In the example we store the CaseMode in a field of the validator for further usage.


In the isValid() method we implement the logic, that determines, whether a String is valid according to a given @CheckCase annotation or not. This decision depends on the case mode retrieved in initialize(). As the Bean Validation specification recommends, we consider null values as being valid. If null is not a valid value for an element, it should be annotated with @NotNull explicitly.




Now, let us go back to bean and add our custom constraint as follows.

package domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import myConstraints.CaseMode;
import myConstraints.CheckCase;

@Entity
@Table(name = "validatorexample4")
public class validatorexample4 {

@Id
@GeneratedValue
@Column(name = "ID")
private int ID;

@Column(name = "FirstName")
@CheckCase(value = CaseMode.UPPER, message="First Name should be in upper case")
private String firstName;

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

}

Now, in order to test our code, we will create our test class as follows

package test;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.Session;
import HibernateUtilities.HibernateUtil;
import domain.validatorexample4;

public class Test {
public static void main(String[] args) {


validatorexample4 v1 = new validatorexample4();
v1.setFirstName("a");

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<validatorexample4>> constraintViolations = validator
.validate(v1);

// printing the results
for (ConstraintViolation<validatorexample4> constraintViolation : constraintViolations) {
System.out.println(constraintViolation.getPropertyPath() + " -> "
+ constraintViolation.getMessage());
}
Session session = HibernateUtil.beginTransaction();
session.save(v1);
HibernateUtil.CommitTransaction();

}
}

Now right click test.java and select run as Java Application. You can see the following output and shows the validation constraints.

2 [main] INFO org.hibernate.validator.util.Version - Hibernate Validator 4.0.2.GA
13 [main] INFO org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
firstName -> First Name should be in upper case
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into validatorexample4 (FirstName) values (?)










That’s all


Project Structure:
image

Read More
Posted in | No comments

Wednesday, 29 August 2012

Hibernate Validator Example 2

Posted on 22:35 by Unknown

In this example, we will see some more validation constraints such as @email, @past, @length, etc. And also we will also define custom error message.

Environment


  1. Eclipse 3.7 Indigo IDE
  2. Hibernate 4.1.1
  3. JavaSE 1.6
  4. MySQL 5.1

Step 1:
Let us set the environment. Follow this post to set up Hibernate with java in eclipse IDE.
Step 2:
We need to add some more jar files for Validator. Please follow the steps

  1. Right click on Project and Select Properties.
  2. Select Java Build Path.
  3. Click “Add External JARs..” and include the following jar files.

hibernate-validator-4.0.2.GA.jar
hibernate-validator-annotation-processor-4.1.0.Final.jar
slf4j-simple-1.4.2.jar
log4j-1.2.15.jar
slf4j-api-1.4.2.jar
validation-api-1.0.0.GA.jar

Step 3
In the mysql, create the following table.

CREATE TABLE `validatorexample3` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `FirstName` VARCHAR(255) DEFAULT NULL,
  `LastName` VARCHAR(255) DEFAULT NULL,
  `BirthDate` DATE DEFAULT NULL,
  `CustomerNumber` VARCHAR(255) DEFAULT NULL,
  `SSN` VARCHAR(255) DEFAULT NULL,
  `Email` VARCHAR(255) DEFAULT NULL,
  `zip` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=latin1

 

Step 4

Now let us create the java bean for the above table.
package domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name = "validatorexample3")
public class validatorexample3 {

@Id
@GeneratedValue
@Column(name = "ID")
private int ID;

@NotNull(message="First name cannot be empty")
@Size(min = 2,message="First name is too small")
@Column(name = "FirstName")
private String firstName;

@Length(min = 2, max = 50, message="LastName should be 2 to 50 Characters size")
@Column(name = "LastName")
private String lastName;

@Column(name = "BirthDate")
@Temporal(TemporalType.DATE)
@Past(message="Date of birth should be past date")
private Date birthDate;

@Pattern(regexp = "^[a-zA-Z]{2}-\\d+$", message="Invalid Customer Number")
@Column(name = "CustomerNumber")
private String customerNumber;

@Pattern(regexp= "[0-9]{3}-[0-9]{2}-[0-9]{4}", message="Invalid SSN format")
@Column(name = "ssn")
private String ssn;

@Column(name = "Email")
@org.hibernate.validator.constraints.Email(message="Invalid Email Format")
private String Email;

@NotEmpty
@Length(min = 5, max = 5, message = "{zip.length}")
@Pattern(regexp = "[0-9]+", message="Invalid Zip")
@Column(name = "zip")
private String zip;

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Date getBirthDate() {
return birthDate;
}

public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}

public String getCustomerNumber() {
return customerNumber;
}

public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}

public String getSsn() {
return ssn;
}

public void setSsn(String ssn) {
this.ssn = ssn;
}

public String getEmail() {
return Email;
}

public void setEmail(String email) {
Email = email;
}

public String getZip() {
return zip;
}

public void setZip(String zip) {
this.zip = zip;
}


}





Now let us map this class in the hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Mapping Classes -->
<mapping class="domain.validatorexample3" />

</session-factory>
</hibernate-configuration>

Very Important, We need add one more property in the above xml file as follows
<property name="javax.persistence.validation.mode">none</property>



Now let us add our test class.


package test;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

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

import org.hibernate.Session;

import HibernateUtilities.HibernateUtil;
import domain.validatorexample3;

public class Test {
public static void main(String[] args) throws Throwable {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

validatorexample3 v1 = new validatorexample3();
v1.setFirstName("a");
v1.setLastName("012345678900123456789001234567890012345678900123456789001234567890");
v1.setBirthDate(sdf.parse(sdf.format(new Date())+1));
v1.setCustomerNumber("#@3434");
v1.setSsn("3fdfdfdf");
v1.setEmail("asdasdasdsadsad");
v1.setZip("asdasdsadasd");

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<validatorexample3>> constraintViolations = validator
.validate(v1);

// printing the results
for (ConstraintViolation<validatorexample3> constraintViolation : constraintViolations) {
System.out.println(constraintViolation.getPropertyPath() + " -> "
+ constraintViolation.getMessage());
}
Session session = HibernateUtil.beginTransaction();
session.save(v1);
HibernateUtil.CommitTransaction();

}
}



Now right click test.java and select run as Java Application. You can see the following output and shows the validation constraints default message.


2 [main] INFO org.hibernate.validator.util.Version - Hibernate Validator 4.0.2.GA
12 [main] INFO org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
Email -> Invalid Email Format
lastName -> LastName should be 2 to 50 Characters size
birthDate -> Date of birth should be past date
zip -> {zip.length}
zip -> Invalid Zip
firstName -> First name is too small
ssn -> Invalid SSN format
customerNumber -> Invalid Customer Number

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into validatorexample3 (Email, BirthDate, CustomerNumber, FirstName, LastName, ssn, zip) values (?, ?, ?, ?, ?, ?, ?)





That’s all.


Project Structure


image

Read More
Posted in | No comments

Hibernate Validator Examples

Posted on 10:44 by Unknown
Let us some examples for Hibernate validator
Here is the introduction notes from the hibernate documentation
Bean Validation standardizes how to define and declare domain model level constraints. You can, for example, express that a property should never be null, that the account balance should be strictly positive, etc. These domain model constraints are declared in the bean itself by annotating its properties. Bean Validation can then read them and check for constraint violations. The validation mechanism can be executed in different layers in your application without having to duplicate any of these rules (presentation layer, data access layer). Following the DRY principle, Bean Validation and its reference implementation Hibernate Validator has been designed for that purpose.
The integration between Hibernate and Bean Validation works at two levels. First, it is able to check in-memory instances of a class for constraint violations. Second, it can apply the constraints to the Hibernate metamodel and incorporate them into the generated database schema.
Each constraint annotation is associated to a validator implementation responsible for checking the constraint on the entity instance. A validator can also (optionally) apply the constraint to the Hibernate metamodel, allowing Hibernate to generate DDL that expresses the constraint. With the appropriate event listener, you can execute the checking operation on inserts, updates and deletes done by Hibernate.
When checking instances at runtime, Hibernate Validator returns information about constraint violations in a set of ConstraintViolations. Among other information, the ConstraintViolation contains an error description message that can embed the parameter values bundle with the annotation (eg. size limit), and message strings that may be externalized to a ResourceBundle.
Example 1:
In the first example, we will see very basic not null constraint validation. Here is the Step by Step Tutorial.
Example 2:
In the second example, we will see some more constraint validation. Here is the Step by Step Tutorial.
Example 3:
In this example, we will see how we can create our custom constraint validation. Here is the Step by Step Tutorial.
Example 4:
In this example, we will see how we can create our custom constraint @Required. Here is the Step by Step Tutorial.
Example 5:
In this example, nothing is new, we will take care example 2 and will use the utility class to perform validation. Here is the Step by Step Tutorial.
Read More
Posted in Hibernate Validator | No comments

Hibernate Validator Example 1

Posted on 09:32 by Unknown
In this example, we will see very basic validation @NotNull.

Environment


  1. Eclipse 3.7 Indigo IDE
  2. Hibernate 4.1.1
  3. JavaSE 1.6
  4. MySQL 5.1

Step 1:
Let us set the environment. Follow this post to set up Hibernate with java in eclipse IDE.Step 2:
We need to add some more jar files for Validator. Please follow the steps

  1. Right click on Project and Select Properties.
  2. Select Java Build Path. 
  3. Click “Add External JARs..” and include the following jar files.
hibernate-validator-4.0.2.GA.jar 
hibernate-validator-annotation-processor-4.1.0.Final.jar
slf4j-simple-1.4.2.jar
log4j-1.2.15.jar
slf4j-api-1.4.2.jar
validation-api-1.0.0.GA.jar

Step 3
In the mysql, create the following table.

CREATE TABLE `validatorexample1` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `FirstName` VARCHAR(255) DEFAULT NULL,
  `LastName` VARCHAR(255) DEFAULT NULL,
  `MiddleName` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=latin1



Step 4

Now let us create the java bean for the above table.
package domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "validatorexample1")
public class validatorexample1 {

@Id
@GeneratedValue
@Column(name = "ID")
private int ID;

@Column(name = "FirstName")
@NotNull private String firstName;

@Column(name = "LastName")
@NotNull
private String lastName;

@Column(name = "middleName")
private String middleName;

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getMiddleName() {
return middleName;
}

public void setMiddleName(String middleName) {
this.middleName = middleName;
}

}


Now let us map this class in the hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Mapping Classes -->
<mapping class="domain.validatorexample1" />

</session-factory>
</hibernate-configuration>

Very Important, We need add one more property in the above xml file as follows
<property name="javax.persistence.validation.mode">none</property> 




Now let us add our test class.

package test;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.Session;
import domain.*;
import HibernateUtilities.*;

public class Test {
public static void main(String[] args) {

validatorexample1 v1 = new validatorexample1();
v1.setFirstName("John");
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<validatorexample1>> constraintViolations = validator
.validate(v1);

// printing the results
for (ConstraintViolation<validatorexample1> constraintViolation : constraintViolations) {
System.out.println(constraintViolation.getPropertyPath() + " -> "
+ constraintViolation.getMessage());
}
Session session = HibernateUtil.beginTransaction();
session.save(v1);
HibernateUtil.CommitTransaction();

}
}

Now right click test.java and select run as Java Application. You can see the following output and shows the validation constraints default message.
2 [main] INFO org.hibernate.validator.util.Version - Hibernate Validator 4.0.2.GA
13 [main] INFO org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
lastName -> may not be nulllog4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into validatorexample1 (FirstName, LastName, middleName) values (?, ?, ?)


That’s all.

Project Structure

image
Read More
Posted in | No comments

Thursday, 16 August 2012

ZK Examples Index Page

Posted on 03:49 by Unknown
ZK File Upload Simple example to upload PDF file in the server and show the content using iframe - MVVM  
ZK Tab box Load Tab box Content on Demand Using MVVM  (Onselect Event)  
ZK Grid ZK Grid inline Editing with Add New and Delete action  
ZK List box ZK List box inline Editing with Add New and Delete action  
ZK Upload ZK Dropupload example  
ZK Report Create a Report with ZK using iReport 5.1.0 and JasperReports  
ZK Menu ZK Dynamic Menu Part 1 Demo
ZK Tree ZK Dynamic Menu Part 2 Using Tree Component Demo
ZK Group Box ZK Dynamic Menu Part 3 Using Group Box and Tool Bar Button Demo
ZK Tab Box ZK Dynamic Menu Part 4 Using Tab box and Tool Bar Button Demo
ZK Menu ZK Dynamic Menu Part 5 Using Tab Box, Tool Bar and Group Box Demo
ZK Tree ZK Dynamic Menu Part 3 Using Group Box and Tool Bar Button Demo
ZK ListBox Move List box item up and Down using MVVM Design Pattern  
ZK ListBox List Item Double click event on selected Item using MVVM  
ZK Combo MVC Two combo Box – Fill second combo based on first combo selection  
ZK Validation Simple Example for ZK Input Form Validation  
ZK MVC Listing Search using MVC Pattern Demo
ZK MVC Passing arguments Part 1, This article will focus on the How to pass some arguments from one window(Parent) to modal window(Child) where child window does not have any controller attached. Demo
ZK MVC Passing arguments Part 2, This article will focus on the How to pass some arguments from one window(Parent) to modal window(Child) where child window attached to the controller and we will receive the arguments in the controller and display back to UI. Demo
ZK MVC Passing arguments Part 3, This article will focus on the How to pass some arguments from one window(Parent) to modal window(Child) where child window attached to the controller and we will receive the arguments in the controller and display back to UI. Same as Part 2, but we will use ZK ‘s annotated data binding manager utility. Demo
ZK MVC Passing arguments Part 4, This article will focus on the How to return values from the child window (Modal) to the Calling Parent Window using ZK Event Queues concept. Demo
ZK MVC Passing arguments Part 5, This article will focus on the How to return values from the child window (Modal) to the Calling Parent Window using ZK Send Event Demo
ZK MVC Passing arguments Example on Passing arguments in MVC Demo
ZK MVVM Passing arguments Part 1, This article will focus on the How to pass some arguments from one window(Parent) to modal window(Child) where child window does not have any VM attached. Demo
ZK MVVM Passing arguments Part 2, This article will focus on the How to pass some arguments from one window(Parent) to modal window(Child) where child window attached with VM and arguments are received in the VM and update the UI. Demo
ZK MVVM Passing arguments Part 3, This article will focus on the How to pass some arguments from one window(Parent) to modal window(Child) where child window attached with VM and arguments are received in the VM and update the UI. After child window is closed, we will return the value to the parent window. Demo
ZK MVVM Passing arguments Part 4, In this post, we will see how we can pass parameter between two zul files attached by MVVM using URL Redirect Demo


ZK CSS

ZK Button Stylish Button created using ZK Link component. Demo
ZK Button Part 2 Stylish Button created using ZK Link component. Demo
ZK Button Part 3 Stylish Button created using ZK Link component. Demo
ZK Button ZK Fancy Buttons Demo
ZK TextBox Small Search Box. Demo
ZK TextBox Big Search Box. Demo
ZK TextBox CSS3 Search Box. Demo
ZK Login Sample Login Form Design in ZK  
ZK Grid Customize ZK Grid CSS  
ZK Tab Box Tabbed Dialog Form - 2 Demo
ZK Tab Box Tabbed Dialog Form - 1 Demo
ZK Tab Box Navigation Menu  
ZK Menu ZK Vertical Menu  
ZK Form ZK Form Design CRUD Example  
ZK Form Search Screen Example  
ZK Form Multi Column Big Screen Design  
ZK Search ZK Search Box  
ZK Button ZK Button CSS Customization  
ZK Window ZK Modal Window CSS Customization  
ZK ListBox ZK Listbox CSS  
ZK Panel ZK Panel CSS Customization  
ZK Messagebox ZK Message box CSS  
ZK ToolBar ZK Tabbox with Tool Bar Button  
CSS File How to Refer External CSS File in ZUL  
ZK Button Button Collection  
ZK Window ZK Window CSS  
ZK Group Box Group Box with Collapse and Expand Button in the Right  


ZK Small Application

ZK MVVM CRUD Example without DB Connection
Step by step tutorial on ZK MVVM CRUD Operation without any DB Connection. online Demo here

ZK MVVM With Spring + JPA + Hibernate Entity Manager
Step by step Tutorial on how to Integrate ZK With spring and JPA (Hibernate vendor)

ZK MVVM With Spring + Hibernate 4 API Direct
Step by step Tutorial on how to Integrate ZK With spring and Hibernate API

 

ZK MVC CRUD With Spring 3 + JPA + Hibernate 4 Entity Manager.
A simple CRUD Application based on JPA. Step by step Tutorial on how to create simple CRUD application using ZK as Presentation layer with Spring 3 and JPA (Hibernate vendor).

 

ZK + Spring Security Custom Login form.
Step by step Tutorial on how to integrate ZK and Spring security


ZK + Spring + MVVM + Hibernate - Small Application

Highlights
1. ZK Maven Project Steps
2. Spring Security integration with custom login form
3. Spring and Hibernate integration
4. Generic DAO and Service Layer
5. Theme customization by each user
6. jQuery integration with ZK Framework
7. Store Image in the Database
8. Validation using Hibernate Validator

Read More
Posted in ZK Framework | No comments
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • ZK Example for inline Editing with Add New and Delete
    I am quite impressed on this demo from ZK . But adding new record and delete existing record is missing as part of typical CRUD. So i thoug...
  • EDI 5010 Documentation 837 Professional - Loop 2010BB Payer Name
    2010BB Payer Name          In this loop, all the information will be taken from Insurance master screen. Take a look of our sample screen...
  • EDI 5010 Documentation–837 - BHT - Beginning of Hierarchical Transaction
    BHT – Beginning of Hierarchical Transaction Loop Seg ID Segment Name Format Length Ref# Req Value   BHT Beginning of Hier...
  • Hibernate Validator Example 2
    In this example, we will see some more validation constraints such as @email, @past, @length, etc. And also we will also define custom error...
  • ZK Passing Parameter between two files using MVVM–Part 1
    Overview This is the first series of articles about Passing parameter between two zul files using MVVM Design pattern .This article will fo...
  • MVVM Command annotation and Notify change example
    Here is an example, how to pass parameter on a zul through MVVM Command binding annotation. ZK URL http://books.zkoss.org/wiki/ZK%20Develo...
  • History of Present Illness
    HPI - One of the main component of Clinical History. What is an HPI ? The history of present illness (HPI) is a chronological description...
  • Patient Demographics
    Patient browse (search) is the key element for any EMR / PMS Software. In my past 15 years experience, i involved more than 5 times in desig...
  • ViewModel Class Java Annotation @Init, @NotifyChange, @Command
    In following sections we'll list all syntaxes that can be used in implementing a ViewModel and applying ZK bind annotation. The ZK binde...
  • Good Website Design Links
    Form Design Label Placement in Forms International Address Fields in Web Forms 40 Eye-Catching Registration Pages blog-comment-form-...

Categories

  • Billing Process
  • C Workbook
  • C++ Workbook
  • Eclipse Tips
  • EDI 5010
  • EMR Appointment Features
  • EMR Labs Stuff
  • EMR PMS Links
  • EMR Use cases
  • EMR Vital Sign
  • Good Website Design
  • Hibernate Criteria Queries
  • Hibernate Introduction
  • Hibernate Introduction Setup
  • Hibernate Mapping
  • Hibernate POC
  • Hibernate Validator
  • Hibernate–Java Environment setup
  • HPI
  • Java
  • Maven
  • MU Certification
  • NPI
  • PQRS
  • Practice Management System
  • Spring Security
  • Tech Links
  • Today Tech Stuff
  • zk
  • ZK Hibernate
  • ZK 5 Databinding
  • ZK Application
  • ZK Calling Another ZUL
  • ZK CheckBox
  • ZK CreateComponents
  • ZK CSS
  • ZK extended Components
  • ZK Foreach
  • ZK Forum Posts
  • ZK Framework
  • ZK Hibernate Setup
  • ZK ID Space
  • ZK Include
  • ZK Installation
  • ZK iReport
  • ZK Layout
  • ZK Listitem Pagination
  • ZK Message Box
  • ZK MVC
  • ZK MVC Combox Box
  • ZK MVC CRUD Examples
  • ZK MVC Listbox
  • ZK MVVM
  • ZK MVVM Combo
  • ZK MVVM CRUD
  • ZK MVVM ListBox
  • ZK Spring
  • ZK TextBox

Blog Archive

  • ►  2013 (105)
    • ►  December (3)
    • ►  September (7)
    • ►  August (13)
    • ►  July (1)
    • ►  June (11)
    • ►  May (3)
    • ►  April (14)
    • ►  March (19)
    • ►  February (21)
    • ►  January (13)
  • ▼  2012 (177)
    • ►  December (1)
    • ►  November (13)
    • ►  October (19)
    • ►  September (24)
    • ▼  August (26)
      • Hibernate Validator - Creating custom constraints ...
      • Hibernate Validator - Creating custom constraints...
      • Hibernate Validator Example 2
      • Hibernate Validator Examples
      • Hibernate Validator Example 1
      • ZK Examples Index Page
      • Hibernate n+1 problem
      • MVVM Command annotation and Notify change example
      • EMR Most Commonly used Vital sign
      • ZK Hibernate one to Many annotation mapping bidire...
      • EDI 5010 Documentation – 837 Professional GE Funct...
      • One to many mapping using bidirectional relationsh...
      • Sample HL7 Files
      • LAB Test Panels
      • EMR In-house Lab workflow
      • One to many mapping using bidirectional relationsh...
      • Hibernate–Java Environment setup
      • Hibernate Mapping one to Many–Some useful explanat...
      • EDI 5010 Documentation 837 Professional - Loop 233...
      • EDI 5010 Documentation 837 Professional - Loop 232...
      • EDI 5010 Documentation 837 Professional - Loop 230...
      • EDI 5010 Documentation 837 Professional - Loop 230...
      • EDI 5010 Documentation 837 Professional - Loop 230...
      • EDI 5010 Documentation 837 Professional - Loop 230...
      • EDI 5010 Documentation 837 Professional - Loop 230...
      • EDI 5010 Documentation – 837 Professional SE Trans...
    • ►  July (6)
    • ►  June (37)
    • ►  May (30)
    • ►  April (16)
    • ►  March (1)
    • ►  January (4)
  • ►  2011 (5)
    • ►  December (1)
    • ►  November (1)
    • ►  July (1)
    • ►  June (1)
    • ►  April (1)
  • ►  2010 (1)
    • ►  September (1)
Powered by Blogger.

About Me

Unknown
View my complete profile