Requirement Constraints

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

Saturday, 1 September 2012

Hibernate Validator - Capture the exception using Utility Class

Posted on 07:01 by Unknown
In this post, nothing is new, we will take care example 2 and will use the utility class to perform validation. And this Utility class will just return the list of violated constraints and we can show the same
to end user whichever the way we want.  Thanks to Andriy Redko {devmind}

Now Let us Start

Environment

  • Eclipse Indigo 3.7 IDE
  • Hibernate 4.1.1
  • Java 1.6
  • 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 JAR” 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 MYSQL, create the following table
CREATE TABLE `validatorexample6` (
`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;

Now let us create all the java files

1. validatorexample6
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 = "validatorexample6")
public class validatorexample6 {

@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;
}


}

2. HibernateUtil.java

package HibernateUtilities;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static Configuration getInitConfiguration() {
Configuration config = new Configuration();
config.configure();
return config;
}

public static Session getSession() {
if (factory == null) {
Configuration config = HibernateUtil.getInitConfiguration();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
config.getProperties()).buildServiceRegistry();
factory = config.buildSessionFactory(serviceRegistry);
}
Session hibernateSession = factory.getCurrentSession();
return hibernateSession;
}

public static Session beginTransaction() {
Session hibernateSession;
hibernateSession = HibernateUtil.getSession();
hibernateSession.beginTransaction();
return hibernateSession;
}

public static void CommitTransaction() {
HibernateUtil.getSession().getTransaction().commit();
}

public static void closeSession() {
HibernateUtil.getSession().close();
}

public static void rollbackTransaction() {
HibernateUtil.getSession().getTransaction().rollback();
}

}

3. ValidatorUtil.java

package utility;

import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;

public class ValidatorUtil {

private final ValidatorFactory factory;

public ValidatorUtil() {
factory = Validation.buildDefaultValidatorFactory();
}

public <T> HashSet<ConstraintViolation<?>> validate(final T instance) {
final Validator validator = factory.getValidator();

final Set<ConstraintViolation<T>> violations = validator.validate(
instance, Default.class);

if (!violations.isEmpty()) {
final Set<ConstraintViolation<?>> constraints = new HashSet<ConstraintViolation<?>>(
violations.size());

for (final ConstraintViolation<?> violation : violations) {
constraints.add(violation);
}

return (HashSet<ConstraintViolation<?>>) constraints;
}
return null;
}

}

4. 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">1234</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>

<property name="javax.persistence.validation.mode">none</property>

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

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

5. Test.Java

package test;

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

import javax.validation.ConstraintViolation;
import org.hibernate.Session;
import utility.ValidatorUtil;
import HibernateUtilities.HibernateUtil;
import domain.validatorexample6;

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

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

validatorexample6 v1 = new validatorexample6();
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");

final Set<ConstraintViolation<?>> constraints = new ValidatorUtil()
.validate(v1);

for (final ConstraintViolation<?> violation : constraints)
{
System.out.println(violation.getPropertyPath() + " -> "
+ violation.getMessage());
}
Session session = HibernateUtil.beginTransaction();
session.save(v1);
HibernateUtil.CommitTransaction();

}
}

Now you run test.java and check the console

Project Structure

 image

Download source here

Email ThisBlogThis!Share to XShare to Facebook
Posted in | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (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)
      • Claims adjudication and payment
      • EDI 5010 Documentation 837 Professional - Loop 240...
      • EDI 5010 Documentation 837 Professional - Loop 233...
      • EDI 5010 Documentation 837 Professional - Loop 231...
      • EDI 5010 Documentation 837 Professional - Loop 231...
      • EDI 5010 Documentation 837 Professional - Loop 231...
      • How to install Maven in the Windows
      • EDI 5010 Documentation 837 Professional - Loop 200...
      • EDI 5010 Documentation 837 Professional - Loop 201...
      • EDI 5010 Documentation – 837 Professional IEA Inte...
      • EDI 5010 Documentation 837 Professional - Loop 201...
      • EDI 5010 Documentation 837 Professional - LOOP 200...
      • Some Important Master screens for PMS
      • EDI 5010 Documentation 837 Professional - Loop 201...
      • EDI 5010 Documentation–837 Loop 2000A - HL–Billing...
      • Physician Quality Reporting System - PQRS
      • EDI 5010 Documentation 837 Health care claim : Pro...
      • EDI 5010 Documentation 837 Professional - Loop 100...
      • EDI 5010 Documentation 837 Professional - Loop 100...
      • EDI 5010 Documentation–837 - BHT - Beginning of Hi...
      • EDI 5010 Documentation–837 ST–Transaction set Header
      • EDI 5010 Documentation–837 GS – Functional Group H...
      • Hibernate Validator - Capture the exception using ...
      • EDI 5010 Documentation–837 Professional - ISA – In...
    • ►  August (26)
    • ►  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