A POJO is simply an object built using a Java class that does not implement any special interfaces such as those defined by the EJB 2 framework. An example of a POJO is a class composed by only:
- Properties, representing the object’s state.
- Getter and setter methods for the properties.
- Business methods, representing behaviour.
Some properties can represent associations with other POJOs. Here is an example of implementation of the
Person
entity using a POJO:
public class Person {
//1. properties
private String firstName;
private String secondName;
private Address address;
//2. getters and setters
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
// ... the other getters and setters
//3. business methods
public int computeAge() {
//here the business logic to compute the person's age
}
}
As you can see the address
property represents an association to another hypothetical POJO.
That’s all! Code that handles database connections and so on shouldn’t be contained within a POJO.
There are many advantages in using POJOs. First of all they’re simple. Second they’re very suitable to represent domain models. Many tools, like Hibernate, work best with domain models implemented using POJOs.