Use of validate in Hibernate

Source: Internet
Author: User
Tags valid email address

Original link: http://blog.csdn.net/xing_sky/article/details/8484551

The first is to add the following two packages

Hibernate-validator-4.1.0.final.jar
Validation-api-1.0.0.ga.jar

An Javax.validation.ConstraintViolationException exception is thrown if an add, update, or delete operation is made when the validation is not passed

Here is the class for testing

Model2:

Java code

Import javax.persistence.Entity;

Import Javax.persistence.GeneratedValue;

Import Javax.persistence.GenerationType;

Import Javax.persistence.Id;

Import Javax.persistence.ManyToOne;

Import javax.persistence.Table;

Import Javax.persistence.TableGenerator;

Import Javax.validation.Valid;

Import Javax.validation.constraints.Max;

Import Javax.validation.constraints.Min;

Import Javax.validation.constraints.NotNull;

Import javax.validation.constraints.Size;

Import Org.hibernate.validator.constraints.Email;

Import Org.hibernate.validator.constraints.URL;

@Entity

@Table (name= "T_model2")

@TableGenerator (name= "MyTable", initialvalue= 1, allocationsize= 1)

public class Model2 {

private int id;

private String name;

Private String address;

Private String PhoneNumber;

Private String Email;

private int age;

Private Model3 model3;

Private String URL;

@Id

@GeneratedValue (generator= "MyTable", strategy=generationtype.table)

public int getId () {

return ID;

}

public void setId (int id) {

this. id = ID;

}

@NotNull (message= "name cannot be empty! " )

Public String GetName () {

return name;

}

public void SetName (String name) {

this. Name = name;

}

@NotNull (message= "address cannot be empty!) " )

Public String getaddress () {

return address;

}

public void setaddress (String address) {

this. Address = address;

}

@Size (max= One, min= one, message= "can only be 11 bits long! " )

Public String Getphonenumber () {

return phonenumber;

}

public void Setphonenumber (String phonenumber) {

this. PhoneNumber = PhoneNumber;

}

@Email (message= "Email address is invalid! " )

@NotNull (message= "email address cannot be empty! " )

Public String Getemail () {

return email;

}

public void Setemail (String email) {

this. email = email;

}

@NotNull (message = "MODEL3 cannot be empty!") " )

@Valid

@ManyToOne

Public Model3 GetModel3 () {

return model3;

}

public void SetModel3 (Model3 model3) {

this. Model3 = Model3;

}

@Min (value=, message= "must be over 18 years old! " )

@Max (value=, message= "age cannot be more than 30 years old! " )

public int getage () {

return age;

}

public void Setage (int.) {

this. Age = age;

}

@URL (message= "Invalid URL address")

@NotNull (message = "URL cannot be empty! " )

Public String GetUrl () {

return URL;

}

public void SetUrl (String URL) {

this. url = URL;

}

}

Model3:

Java code

Import javax.persistence.Entity;

Import Javax.persistence.GeneratedValue;

Import Javax.persistence.Id;

Import javax.persistence.Table;

Import Javax.validation.constraints.NotNull;

@Entity

@Table (name= "T_model3")

public class Model3 {

private int id;

private String name;

@Id

@GeneratedValue

public int getId () {

return ID;

}

public void setId (int id) {

this. id = ID;

}

The name of the @NotNull (message= "MODEL3 cannot be empty! " )

Public String GetName () {

return name;

}

public void SetName (String name) {

this. Name = name;

}

}

Test class:

Java code

Import Org.springframework.context.ApplicationContext;

Import Com.tiantian.test.model.Model2;

Import Com.tiantian.test.service.Model2Service;

Import Com.tiantian.test20110430.util.Util;

public class Test1 {

public static void Main (String args[]) {

ApplicationContext context = Util.getcontext ();

Model2service service = Context.getbean (Model2service.class);

Model2 model = new Model2 ();

Model.setname ("Hello");

Model.setemail ("[email protected]");

Model.setaddress ("Changsha, Hunan");

Model.setphonenumber ("15012345678");

string result = Util.validatemodel (model);//Returns the validation result, the validation result is a string, if there is an error, the length of the string is greater than 0

SYSTEM.OUT.PRINTLN (result);

if (result.length () = = 0)//verification does not add when not passed

Service.add (model);

}

}

The Util class used above:

Java code

Import Java.util.Iterator;

Import Java.util.Set;

Import javax.validation.ConstraintViolation;

Import javax.validation.Validation;

Import Javax.validation.Validator;

Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;

public class Util {

private static ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml");

public static ApplicationContext GetContext () {

return context;

}

public static String Validatemodel (Object obj) {//Validates an object

StringBuffer buffer = new StringBuffer (64); Used to store the error message after validation

Validator Validator = Validation.builddefaultvalidatorfactory ()

. Getvalidator ();

set<constraintviolation<object>> constraintviolations = Validator

. validate (obj);//Validation of an object, in fact, you can only verify that one of the properties of the

iterator<constraintviolation<object>> iter = constraintviolations

. iterator ();

while (Iter.hasnext ()) {

String message = Iter.next (). GetMessage ();

Buffer.append (message);

}

return buffer.tostring ();

}

}

Here are some of the main annotations:

Java code

@AssertTrue//For Boolean fields, this field can only be true

@AssertFalse//The value of this field can only be false

@CreditCardNumber//A rough verification of the credit card number

@DecimalMax//can only be less than or equal to this value

@DecimalMin//can only be greater than or equal to this value

@Digits (integer= 2, fraction= 20)//Check whether the number is a number of integers, fractions, and decimal digits.

@Email//Check if it is a valid Email address

@Future//Check if the date of the field is a date that belongs to the future

@Length (min=,max=)//Check whether the length of the field to which it belongs is between Min and Max, only for strings

@Max//The value of the field can only be less than or equal to the value

@Min//The value of the field can only be greater than or equal to this value

@NotNull//cannot be null

@NotBlank//cannot be empty, and whitespace is ignored when checking

@NotEmpty//cannot be empty, where null is the empty string

@Null//Check that the field is empty

@Past//Check the date of the field is in the past

@Size (min=, max=)//Check if the Size of the field is between Min and Max, which can be a string, array, collection, map, and so on

@URL (protocol=,host,port)//Check if it is a valid URL, and if Protocol,host is provided, the URL must also meet the conditions provided

@Valid//The annotation is used whenever the field is a field that contains a collection of other objects or a map or array, or if the field is a reference directly to a different object.

This will also check the object referenced by the field while checking the current object

Use of validate in Hibernate (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.