index-1-1.jpg
  • Aurora 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.

0 views0 comments

Recent Posts

See All

Get and Load Methods in Hibernate

Both Get and Load methods in hibernate fetch row from databases. The functionality is similar but there is a difference between the way they work. hibernateSession.get() This method will return the re

Many To Many Relationship Using Annotations

This article is about how to write many to many relationships using annotations in hibernate. Many to many means that we can have many rows in one table against many rows in another table. Here is an

Many To Many Relationship Using XML

This article is about how to write many to many relationship using XML in hibernate. Many to many means that we can have many rows in one table against many rows in another table. In my previous artic