Problem

You want to isolate data access and manipulation in a separate layer, while retaining full encapsulation and object integrity.

When dealing with object-relational persistence, there is often a need for the DAO implementation to modify data on the domain (a.k.a. business) object that is being persisted, e.g. when a new object is being inserted into a relational database table, it can sometimes be auto-assigned a surrogate primary key, a.k.a. an identity column. In a properly designed entity class, the field representing the primary key should not be modifiable to the public, as this would compromise the integrity of the object's state. In a traditional DAO implementation, the solution has been to break encapsulation and allow the DAO implementation, and hence everyone else, to modify the necessary fields.

Solution

Create the DAO interface as an abstract static inner class of the domain object it persists.

In Java, inner classes have access to the private members of the outer class. This presents a unique opportunity to give the DAO implementation access to select private members, while still isolating the actual persistence behavior in its own class.

Inner Class strategy of the DAO pattern

The abstract DAO super class, will provide protected methods for accessing the private member variables that needs to be available to the DAO sub class implementation. This provides full and separate control over what is exposed to the public and what is exposed to the DAO implementation.

In the example given, the ID and name of the Customer object is available only as a readable properties to the public, thus retaining encapsulation and guaranteeing no change of the object's ID field. At the same time, the DAO implementation is selectively allowed to modify the ID through the protected setId(Customer, Long) method on the DAO abstract class.