Comments
yourfanat wrote: I am using another tool for Oracle developers - dbForge Studio for Oracle. This IDE has lots of usefull features, among them: oracle designer, code competion and formatter, query builder, debugger, profiler, erxport/import, reports and many others. The latest version supports Oracle 12C. More information here.
Cloud Expo on Google News
SYS-CON.TV

2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
JavaBean Validation with javax Annotation and Hibernate Validator
Java EE 6 platform provides a set of annotations for bean validation

As you know modern programming paradigm suggests validating a java bean with annotations. A java bean can be validated in many ways. You can refer to my earlier article on bean validation .But we have to opt for the simplest and the robust one. With the introduction of java annotation feature, programming has become easier and lets developers to write less code. In this article I will show you the significance of Hibernate validator and javax annotation in a java bean. The api provided by hibernate validator and javax annotation has made developer’s life much easier to put validation instantly.

Java EE 6 platform provides a set of annotations for bean validation. This bean validation API can be applied to field and method level to achieve validation. Apart from that Hibernate validator provides some extra validation annotation to ease the development and also it provides the shortcut way define your own custom validation constraints.  The javax bean validation api provides below the most frequently used annotations.

javax.validation.constraints.Digits

javax.validation.constraints.Min

javax.validation.constraints.Max

javax.validation.constraints.NotNull

javax.validation.constraints.DecimalMax

javax.validation.constraints.DecimalMin

javax.validation.constraints.Pattern

javax.validation.constraints.Null

javax.validation.constraints.Size

Hibernate validator provides below the commonly used annotations for validation.

org.hibernate.validator.constraints.URL

org.hibernate.validator.constraints.NotEmpty

org.hibernate.validator.constraints.NotBlank

org.hibernate.validator.constraints.Length

org.hibernate.validator.constraints.Email

org.hibernate.validator.constraints.CreditCardNumber

In case of product or project development we have to use both the annotations for bean validation. It is always recommended to use the relevant annotations in the field level of the java bean as it increases the readability and minimizes the burden of bug fixing and maintenance problem.

How to do

In order to achieve bean validation, you have to use javax bean validation api, hibernate validator api and logging api. For the usage of this validation, you have use the following jar files mentioned below.

hibernate-validator-4.3.1.Final.jar

jboss-logging-3.1.0.CR2.jar

validation-api-1.0.0.GA.jar

All the above jar files can be downloaded from the site “mvnrepository.com”. If you are using maven project, you have to use the following dependencies as mentioned below.

<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.11</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-validator</artifactId>

<version>4.3.1.Final</version>

</dependency>

</dependencies>

The dependency for junit is optional as it depends upon your project requirement.

Let us see a brief structure of a bean provided with various annotations.

public class Bean1 {

// ~~~~~~~~~~ javax annotations for validation ~~~~~~~~~~

@Digits(integer = 2, fraction = 0, message = "The value of age can not be more than 2 digits")

@Min(value = 18, message = "The minimum age should be 18")

@Max(value = 50, message = "The maximum age can not more than be 50")

private int age;

@NotNull(message = "First Name can not be null ... ")

private String firstName;

@DecimalMax(value = "99999.999", message = "The decimal value can not be more than 99999.999 ")

@DecimalMin(value = "1.00", message = "The decimal value can not be less than 1.00 digit ")

private float amount = 0f;

@NotNull

@Pattern(regexp = "^\\d{6}", message = "Invalid zip code, Indian zip code should be 6 digit")

private String zipCode;

// ~~~~~~~~~~ Hibernate provided annotations for validation ~~~~~~~~~~

@CreditCardNumber(message = "Invalid credit card number")

private String creditCard;

@Email(message = "Invalid email id")

private String emailId;

@Length(max = 50, min = 10, message = "The message description should be within 10 to 50 characters")

private String description;

@NotBlank(message = "SurName can not be blank")

// It is only applicable to String

private String surName;

@NotEmpty(message = "The list can not be empty")

private List<String> countryList;

@URL(message = "Invalid website address")

private String website;

// ~~~~~~~~~~ Custom annotations for validation ~~~~~~~~~~

@Password

private String password;

@IBAN

private String ibanActNo;

// ~~ getter and setter methods below

}

The above java class contains many fields which require validations. If the above bean is populated with data, we have to validate the bean with the default validator provided by hibernate api. The brief code structure is given below.

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

Validator validator = factory.getValidator();

Set<ConstraintViolation<Bean1>> set = validator.validate(bean);

noOfViolations = set.size();

if (noOfViolations != 0)

throw new BeanValidationFailedException(set);

The above code is very precise and provides the a set of violations. This is all about the default annotations provided. What about your own custom annotations which may be required as per your project requirements ? Javax bean validation api provides the easiest way to define and integrate your own annotations for validation. Let us take an example of password. The rule for password is it should be within 6 to 20 characters, one special character, one upper case and one numeric character. For this purpose we have define an annotation called “Password” and we have to define one java class called “PasswordValidator” by implementing “javax.validation.ConstraintValidator”. That’s it. You are done now. You can now freely use your annotation n any java bean. Let us see the brief code structure for the above.

@Target({ METHOD, FIELD, ANNOTATION_TYPE })

@Retention(RUNTIME)

@Constraint(validatedBy = PasswordValidator.class)

public @interface Password {

/**

* This method is used to provide a default message

*

* @return

*/

String message() default "{Invalid password, valid password : one Upper case, one special char, one number, total length 6 t0 20 chars}";

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

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

}

The above is the password annotation, the password validator class is given below.

public class PasswordValidator implements ConstraintValidator<Password, String> {

public void initialize(Password pwd) {

// do nothing

}

public boolean isValid(String str, ConstraintValidatorContext ctx) {

//Write your own business logic

return validate(str);

}

}

The complete project for the validation can be downloaded from the following link.

Download project https://www.dropbox.com/s/r4dgtz49bxyrpvw/javaxbeanvalidation.zip

You can download the complete project, extract it and import the project as maven project. If you have internet you can run the project with the command “clean compile install”. If you want to manually run the project, run the java class “App.java”.  If you do not want maven project, download all the above mentioned jar files and put the jar files inside a folder called “lib” inside your eclipse project and set the eclipse build path. In this project I have defined two custom annotations, you can also define you own annotations and test the application.

Conclusion

This article is meant for the novice user. It will give you a cleaner approach of using javax annotation and hibernate validator for the bean validation. I hope you will enjoy my article, For any queries contact me on debadatta.mishra@gmail.com.

<>Refences

 

http://docs.oracle.com/javaee/6/api/javax/validation/constraints/package-tree.html

http://docs.oracle.com/javaee/6/api/javax/validation/constraints/package-summary.html

http://docs.jboss.org/hibernate/validator/4.1/api/org/hibernate/validator/constraints/package-summary.html

http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html

About Debadatta Mishra
Debadatta Mishra is a senior Java developer with five years of experience in the field of Java and related technologies. He has written many articles on Java-related technologies on the Internet.

Latest AJAXWorld RIA Stories
In his session at 21st Cloud Expo, James Henry, Co-CEO/CTO of Calgary Scientific Inc., introduced you to the challenges, solutions and benefits of training AI systems to solve visual problems with an emphasis on improving AIs with continuous training in the field. He explored app...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around qualit...
"DivvyCloud as a company set out to help customers automate solutions to the most common cloud problems," noted Jeremy Snyder, VP of Business Development at DivvyCloud, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY...
"Our strategy is to focus on the hyperscale providers - AWS, Azure, and Google. Over the last year we saw that a lot of developers need to learn how to do their job in the cloud and we see this DevOps movement that we are catering to with our content," stated Alessandro Fasan, He...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct ...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON Featured Whitepapers
ADS BY GOOGLE