Obtain an entity reference without initializing its data in JPA: getReference

The ability to obtain a reference to an entity without having to load its data is very important. 

The most common case being the need to create an association between an entity and another, existing entity. 

We achieve this  lazy loading by using EntityManager.getReference(id). With the method “getReference” you will query only for the object ID, you will save some database traffic.

Use getReference method when you just to update some state by setter method without need to know the whole object's state from database. getReference returns a proxy object which uses a powerful feature called automatic dirty checking. For example:
public class Dog {
    private String name;
    private Integer age;
}

public class DogServiceImpl implements DogService {

    public void updateAge(Integer id, Integer newAge) {
        Dog dog = em.getReference(Dog.class, id);
        // dog is a proxy
        dog.setAge(newAge);
    }
}
If you call find method, JPA provider, behind the scenes, will call
SELECT NAME, AGE FROM DOG WHERE ID = ?
UPDATE DOG SET AGE = ? WHERE ID = ?
If you call getReference method, JPA provider, behind the scenes, will call
UPDATE DOG SET AGE = ? WHERE ID = ?
When you call getReference, you will get a proxy object which is provided by JPA provider:
public class DogProxy {

    // JPA provider sets up this field when you call getReference
    private Integer id;

    private String query = "UPDATE DOG SET ";

    private boolean stateChanged = false;

    public void setAge(Integer newAge) {
        stateChanged = true;
        query += query + "AGE = " + newAge;
    }
}
Before transaction commits, JPA provider will check stateChanged flag to decide to update or not. If no row is updated after update statement, JPA provider will throw EntityNotFoundException according to JPA specification.

Featured Post

Updated Coupons / promo codes for Google Apps for Work / Business

To redeem: 1. Sign up for Google Apps   2. Go to your billing settings  3. Choose your payment plan  4. Enter your promo code ...