Using bean Validation in hibernate

baileyhaldwin :

I was wondering if it was possible to use Java Bean Validation in hibernate, and how they integrate with each other.

I have a stack that consists of a Jax-rs API, and JPA in my data layer.

I was wondering if I it could use Java Bean validation to validate my Hibernate Entities, without using Spring.

Could I use the annotations from hibernate along with the ones from the javax.validation.contraints together

for example:

@Column(nullable = false)
@Size(min =8, max = 12)
@NotNull(message = "Phone Number must be entered")
private String phoneNumber;

here I specify that I the column, can't be null through hibernate and the bean validation.

Is this a good practice?

Or is there an alternative to validating data in hibernate, without bean validation like such?

Thorben Janssen :

The Bean Validation specification integrates with Hibernate and all other implementations of the JPA 2.x specification. I explained that in great detail in my article How to automatically validate entities with Hibernate Validator.

Let me give a quick summary:

If you add an implementation of the Bean Validation specification, e.g., Hibernate Validator, to your project, Hibernate automatically triggers the validation before inserting and updating an entity. You can customize that and also trigger validation before removing an entity. I explained that in more details in my article.

You can use all features of the Bean Validation specification, including custom validation rules, to validate your entity attributes. I used that here to validate that the value of an entity attribute is within a defined range and here to check that only one out of 2 associations is set.

The example mapping that you posted in your question is a very good practice! The @Column(nullable = false) part is not strictly necessary because the validation rule already ensures that the attribute can't be null.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147899&siteId=1