Sourabh
Sourabh

Reputation: 59

Spring Hibernate Bean Validation @valid

I know it is not new question in this forum but I am very confused what should i do.

Problem: I am developing one application with spring mvc + hibernate. For server side validation I am using @valid annotation in controller and @null and @notNull annotation in my bean.

e.g

public class User implements Serializable {

    private static final long serialVersionUID = 2158419746939747203L;

    @Id
    @Column(name="USER_ID")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long userId;

    @Column(name="USERNAME", unique = true)
    @NotEmpty @NotNull @Size(min=6, max=20)
    private String username;

    @Column(name="PASSWORD")
    @NotEmpty @NotNull @Size(min=6, max=20)
    private String password;

This validation is happening fine and data is also saving in DB.

But I want to validate unique constraint,referential integrity and other constraint using annotation without any validator class.

Is it possible? if no, then what is best and easiest way to to do it(less coding)? I will appreciate if framework will do it for me.

Upvotes: 0

Views: 1164

Answers (1)

Paul John
Paul John

Reputation: 1661

Saurabh,

For unique constraint in table,

 @Id

You will be able to enforce referential integrity via hibernate annotations as well eg.

@OneToOne(mappedBy = "foo")

Here is an example post

Referential integrity with One to One using hibernate

Here is a very detailed tutorial also exploring the same:

http://www.journaldev.com/2882/hibernate-tutorial-for-beginners-using-xml-annotations-and-property-configurations

You could write a "CustomUniqueConstraintValidator" kinda like mentioned in

http://www.journaldev.com/2668/spring-mvc-form-validation-example-using-annotation-and-custom-validator-implementation

You can also pass in paramters from the annotation to the custom validator. eg.

@CustomValidDate("columnName")

To make a generic class that applies for any field /column 1. YOu can write a generic custom validator 2. use annotaiton parameters (on each class attribute) to pass in the table name and column name. 3. Then in the validator you can use the table name, column name to apply your validation logic (unique etc).

Thanks, Paul

Upvotes: 1

Related Questions