top of page
index-1-1.jpg
Writer's pictureAurora Solutions

TRANSIENT FIELD WITH ANNOTATION VALIDATORS


Recently I got the chance to work with annotation validators @Pattern on transient field. Basically it was a password field which I had to validate first and then encrypt it and set it in another persisted field which I was saving to database. The portion of class looks like this

Class Password{

private String password;

private String encryptedPassword;

 

@Transient

@Pattern(regex=”^[a-zA-Z0-9]*$”)

public String getPassword() { return this.password; }

public void setPassword(String password)

{

this.password = password;

setEncryptedPassword(encryptedMethod(password));

}

 

@Column(name=”password”)

public String getEncryptedPassword() { return encryptedPassword; }

 

private void setEncryptedPassword(String encryptedPassword)

{

this.encryptedPassword = encryptedPassword;

}

}

And I tried to save this password : “qwert” using this code

Password password = new Password();

password.setPassword(“qwert”);

PasswordDAO dao = new PasswordDAO();

dao.save(password);

dao.flush();

To my surprise it did save the password however it should not have done so and thrown an exception.


What is Happening

The problem is that when you call save method of hibernate a new shiny persisted object is returned and created and also copies data from passwordClass instance to that object. The problem is it does not copy transient field value. So you need to copy that transient field value to new persisted object.

How to solve it? Write the following code in order to apply validaiton on transient field.

PasswordDAO dao = new PasswordDAO();

Password password = dao.save(new Password());

password.setPassword(“qwert”);

dao.flush();

This will copy the transient field value to the persisted object and will also throw ConstraintVoilationException if field is not upto rule.

I look forward to hearing suggestions in the comments section.

20 views0 comments

Recent Posts

See All

Commentaires


bottom of page