Let's say you have a collection of Car
objects (database rows), and each Car
has a collection of Wheel
objects (also rows). In other words, Car
→ Wheel
is a 1-to-many relationship.
Now, let's say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following:
SELECT * FROM Cars;
And then for each Car
:
SELECT * FROM Wheel WHERE CarId = ?
In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars.
Alternatively, one could get all wheels and perform the lookups in memory:
SELECT * FROM Wheel
This reduces the number of round-trips to the database from N+1 to 2.
Most ORM tools give you several ways to prevent N+1 selects.
Reference: Java Persistence with Hibernate, chapter 13.
Sometimes you have two entities and there's a relationship between them. For example, you might have an entity called University
and another entity called Student
and a University might have many Students:
The University entity might have some basic properties such as id, name, address, etc. as well as a collection property called students that returns the list of students for a given university:
public class University {
private String id;
private String name;
private String address;
private List<Student> students;
// setters and getters
}
Now when you load a University from the database, JPA loads its id, name, and address fields for you. But you have two options for how students should be loaded:
- To load it together with the rest of the fields (i.e. eagerly), or
- To load it on-demand (i.e. lazily) when you call the university's
getStudents()
method.
When a university has many students it is not efficient to load all of its students together with it, especially when they are not needed and in suchlike cases you can declare that you want students to be loaded when they are actually needed. This is called lazy loading.
Here's an example, where students
is explicitly marked to be loaded eagerly:
@Entity
public class University {
@Id
private String id;
private String name;
private String address;
@OneToMany(fetch = FetchType.EAGER)
private List<Student> students;
// etc.
}
And here's an example where students
is explicitly marked to be loaded lazily:
@Entity
public class University {
@Id
private String id;
private String name;
private String address;
@OneToMany(fetch = FetchType.LAZY)
private List<Student> students;
// etc.
}
Best Answer
I would define ORM as a system to map any data to the object/class structure. That data may come from a system that is aimed to be for persist data, but not mandatory. Imagine a JSON mapper that reads data from a network service into an object.
A persistence framework mostly uses ORM to interface to user code and covers the problematic to make the storage of objects as secure and reliable as possible.
ORM is more generic term than persistence. ORM may live without Persistence but not vicecersa.