Wednesday, December 10, 2008

Adding logic to accessor methods in Hibernate

While reading Java Persistence with Hibernate I came across an interesting fact that Hibernate does not require you to have getter and setter methods. On top of that it does not rely on them to check if the value of a property has changes. This means that you can amend and change your data before giving it away from getter.

Assume you have a Person class and a person has a first and second names, both must be capitalized.

First, you can add logic into your methods, like validation:

public class Person{
   
private String firstName;
   
private String secondName;
   
public String getFirstName(){
       
return firstName;
   
}
   
public void setFirstName(String firstName)
               
throws InvalidNameException{
       
if(!StringUtil.isCapitalized(firstname))
           
throw new InvalidNameException(firstname);
       
this.firstname = firstname;
   
}
}

Second, you can have convenience methods:

public class Person{
   
private String firstName;
   
private String secondName;
   
public String getName(){
       
return firstName + ' ' + secondName;
   
}
   
public void setName(String name){
       
StringTokenizer t = new StringTokenizer(name);
       
firstname = t.nextToken();
       
secondname = t.nextToken();
   
}
}

NOTE:
The only exception is collections! You can not change collection values in your getter and setter methods. Otherwise, Hibernate will issue an UPDATE SQL statement every time it synchronizes with database.

To conclude, you can change a property's value also add logic in your getter/setter methods if and only if the property is not a collection.

No comments: