Object persistence lets an individual object outlive the application process: its data is saved to a store, then used to re-create the object later. In Java applications using relational databases, this usually means mapping object instances to database data and storing them with SQL. section 1.1
The difficulty is that an object model and a relational database represent data differently. An object network cannot simply be placed in one table; its state must be broken into columns with SQL data types. Re-creating an object—or a graph of related objects—requires the reverse mapping. section 1.4
Persisting an association
A User can hold a Set<BillingDetails>, while each BillingDetails can hold a reference back to its User. These Java references give each navigation direction an explicit place in the classes. In a relational database, an association instead uses key values and foreign-key constraints; a many-to-many relationship needs a link table. Saving the objects therefore involves mapping both their values and their relationships. section 1.2.4
CREATE TABLE USER_BILLINGDETAILS (
USER_ID BIGINT,
BILLINGDETAILS_ID BIGINT,
PRIMARY KEY (USER_ID, BILLINGDETAILS_ID),
FOREIGN KEY (USER_ID) REFERENCES USERS(ID),
FOREIGN KEY (BILLINGDETAILS_ID) REFERENCES BILLINGDETAILS(ID)
);
The USER_BILLINGDETAILS table shows how a many-to-many object association becomes pairs of foreign keys in SQL. section 1.2.4
Object/relational mapping (ORM) handles much of this translation, including SQL joins and copying JDBC results into objects or object graphs. A Java ORM solution can use a JPA implementation such as Hibernate; Spring Data can simplify persistence access further. ORM does not remove every persistence task or make every application a good fit for a rich domain model. section 1.4 section 3.1.3
Choose the approach to match the application. Full ORM is most suitable when persistent entities have rich relationships and domain behavior. For applications with few entities or limited interactions, a table-oriented design may be sufficient, and the learning time and overhead of ORM may not be justified. Business-rule objects need not themselves be persistent. section 3.1.3
