Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Built-In Validators in Hibernate

Introduction to Built-In Validators

Hibernate provides a powerful validation framework that allows developers to enforce constraints on entity properties. Built-in validators help ensure that the data stored in the database adheres to specific rules. These validators can be used in combination with annotations to simplify the validation process.

Common Built-In Validators

Hibernate offers several built-in validators that can be applied to entity fields. Below are some of the most commonly used validators:

  • @NotNull: Ensures that a field is not null.
  • @Size: Checks the size of a string, collection, or array.
  • @Min and @Max: Validate numeric fields to ensure they fall within a specific range.
  • @Email: Validates that a string is a valid email address.
  • @Pattern: Validates a string against a specified regular expression.

Using @NotNull Validator

The @NotNull annotation is used to specify that a field must not be null. It is commonly used for required fields.

Example:

Annotating a field with @NotNull:

@NotNull
private String username;

In the above example, the username field is required and cannot be null. If an attempt is made to save an entity with a null username, a validation error will occur.

Using @Size Validator

The @Size annotation restricts the size of a string or collection. It takes two parameters: min and max.

Example:

Annotating a field with @Size:

@Size(min = 2, max = 30)
private String name;

Here, the name field must be between 2 and 30 characters long. If the input does not meet these criteria, validation will fail.

Using @Min and @Max Validators

The @Min and @Max annotations are used to set boundaries on numeric fields.

Example:

Annotating numeric fields:

@Min(18)
private int age;
@Max(65)
private int retirementAge;

In this example, the age field must be at least 18, and the retirementAge must not exceed 65.

Using @Email Validator

The @Email annotation checks if a string is a valid email address format.

Example:

Annotating an email field:

@Email
private String email;

If the email field does not contain a valid email address, the validation will fail.

Using @Pattern Validator

The @Pattern annotation allows you to validate a string against a specific regular expression.

Example:

Annotating a field with @Pattern:

@Pattern(regexp = "^[a-zA-Z0-9._-]+@[a-z]+\\.[a-z]{2,}$")
private String customEmail;

In this case, the customEmail field must match the specified regex pattern to be considered valid.

Conclusion

Built-in validators in Hibernate provide a straightforward way to enforce data integrity and validation rules on entity properties. By using annotations like @NotNull, @Size, @Min, @Max, @Email, and @Pattern, developers can easily define constraints that help maintain high-quality data in their applications.