search
HomeJavajavaTutorialHibernate_Validator detailed introduction

Hibernate_Validator detailed introduction

Jun 20, 2017 am 09:54 AM
hibernatevalidatorstudy

1. Introduction to Hibernate Validator

1.1 Background

At any time, when you want to handle the business logic of an application, data validation is Something you have to consider and face. The application must have some means to ensure that the incoming data is semantically correct. Typically, applications are layered, with different layers being completed by different developers. Many times the same data validation logic will appear in different layers, which will lead to code redundancy and some management issues, such as semantic consistency. In order to avoid such a situation, it is best to bind the validation logic with the corresponding domain model.

Bean Validation defines the corresponding metadata model and API for JavaBean validation. The default metadata is Java Annotations, and the original metadata information can be overwritten and extended by using XML. Bean Validation is a runtime data validation framework, and validation error information will be returned immediately after validation.

Hibernate Validator is the reference implementation of Bean Validation. Hibernate Validator provides implementation of all built-in constraints in the JSR 303 specification, in addition to some additional constraints.

1.2 Constraints in Bean Validation

1.3 Constraints attached to Hibernate Validator

1.4 Advantages of Hibernate Validator

a) The separation of verification logic and business logic reduces program coupling;

b) A unified and standardized verification method eliminates the need for you to write repeated verification code again;

c) You will be more focused on your business and leave all these tedious things aside.

2. Hibernate Validator practice

maven dependency:

< ;dependency>

; org.hibernate

## .Final

2.2 Configuration in SpringMvc

The demo of this article is based on springmvc, which requires Make relevant configurations.

2.3 Add constraint

to JavaBean As shown in the figure, several constraints are added to User: the name is not empty and the length constraint is added; the sex is added with a custom constraint, which will be introduced later; the role constraint is an object embedded constraint. The verification of JSR-303 is based on annotations, and a series of restriction annotations have been defined internally. We only need to mark these annotations on the attributes of the entity class that need to be verified or on their corresponding get methods.

2.4 Custom constraint

As shown in the figure, a ValidSex annotation is defined, and the annotation is marked with the @Constraint annotation , using the @Constraint annotation indicates that we have defined an annotation for restrictions. The validatedBy attribute of the @Constraint annotation is used to specify which ConstraintValidator the current restriction type we define needs to be verified. In the above code, we specified that the validation class of ValidSex restriction type is ValidSexValidator. In addition, it should be noted that there are three attributes that must be defined when we define our own restricted type annotations, such as the message, groups and payload attributes shown in the above code.

2.5 Custom constraint implementation class

As shown in the figure, ConstraintValidator uses generics. It needs to specify a total of two types. The first type is the parameter type of the corresponding initialize method, and the second type is the first parameter type of the corresponding isValid method. From the above two methods, we can see that the initialize method can obtain the attributes of the current restriction type, and the isValid method is used for verification.

2.6 Verify parameters

In the above figure we can see that we have defined a LoginController. The Controller has a processor method validator that handles the validator operation. It needs to receive a User object sent by the client. We are going to use the previous Validator to do this. User object for verification. First we can see that the parameter user received by our validator method is annotated with @Valid. In addition, our processor method must be given a parameter containing Errors, which can be Errors itself, or its subclass BindingResult. Using the Errors parameter tells Spring that errors in form object data verification will be handled by ourselves. Otherwise Spring will throw an exception directly. In this way, when we request the processor method validator, the user object will be verified and the relevant verification information will be stored in the current Errors object. Then we can perform different operations in our processor method depending on whether there is verification exception information. In the above code, we define that we will jump to the login page when there is exception information. In this way, we can display these error messages through the errors tag on the login page.

2.7 Notes

a) If you are verifying an attribute (getter method), you must follow the naming convention of Java Beans (JavaBeans specification);

b) Static Fields and methods cannot be subject to constraint verification;

c) Constraints apply to interfaces and base classes;

d) The target elements defined by constraint annotations can be fields, attributes or types;

e) You can use constraint validation on a class or interface, which will perform state verification on the class or instance that implements the interface;

f) You can use constraint validation on fields and attributes, but you cannot The same constraints are declared repeatedly on fields and related properties (getter methods of fields).

Conclusion: Be kind to everyone around you, because they are the ones who make your life happen.

The above is the detailed content of Hibernate_Validator detailed introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools