A plain old Java object (POJO) is an ordinary Java class used to represent state and behavior without tying its basic design to a framework. In a persistence-capable domain model, it can hold attributes, business methods, and associations to other objects. The aim is transparent persistence: business objects remain usable and testable independently of the persistence mechanism. section 3.2.2 section 3.2.3 section 3.4
POJO does not mean that persistence imposes no rules. A JPA entity needs a database identifier and a no-argument constructor; collection-valued attributes use interfaces such as List or Set rather than concrete implementations. The constructor may be nonpublic, but keeping it at least package-visible allows Hibernate to use runtime-generated proxies. section 3.2.2 section 3.2.3
For a portable persistence-capable class:
- Make it a top-level class, and avoid final on the class and its methods. Hibernate permits some final declarations, but they can prevent proxy-based performance optimizations; JPA's rules are stricter. section 3.2.3
- Keep attributes in private or protected fields, commonly with public or protected getters and setters. Accessors can contain behavior rather than simply return a field. section 3.2.3 section 3.4
- Keep unrelated infrastructure concerns, such as logging, authorization, and transaction demarcation, out of the persistent class. section 3.4
Listing 3.2 POJO implementation of the User class with logic in accessor methods
Path: Ch03/domainmodel/src/main/java/com/manning/javapersistence/ch03/ex02 /User.java public class User { private String firstname; private String lastname; public String getName() { return firstname + ' ' + lastname; } public void setName(String name) { StringTokenizer tokenizer = new StringTokenizer(name); firstname = tokenizer.nextToken(); lastname = tokenizer.nextToken(); } }
The User POJO stores first and last names separately while its name accessor combines or splits them. A property need not be a direct view of one field. section 3.2.3
Model an address as an object
A USERS table can store HOME_STREET, HOME_CITY, and HOME_ZIPCODE while a User POJO holds a homeAddress property of type Address. The extra class gives the domain model a cohesive, reusable representation rather than three unrelated strings. section 5.1.1
Setters are not mandatory for every POJO design. An immutable class can set its values in a constructor and expose no public setters. With field access, Hibernate can load and store its fields directly; an immutable entity mapping can also avoid updates and dirty checking. Not every framework supports POJOs without setters, so check the intended persistence provider. section 5.3.3
