Session: How to Check if There are Any Changes on a Session

Single entity can be checked for changes using hasChanged method, but there is also a possibility to check if there are any changes on a session or even what has changed. Both the hasChanges method and the whatChanged method are available in the advanced session operations.

HasChanges

Property indicates if the session contains any changes. If there are any new, changed or deleted entities.

boolean hasChanges()

Example

try (IDocumentSession session = store.openSession()) {
    Assert.assertFalse(session.advanced().hasChanges());

    Employee employee = new Employee();
    employee.setFirstName("John");
    employee.setLastName("Doe");

    session.store(employee);

    Assert.assertTrue(session.advanced().hasChanges());
}

WhatChanged

Method returns all changes for each entity stored within the session. Including name of the field/property that changed, its old and new value, and change type.

Map<String, List<DocumentsChanges>> whatChanged()
ReturnValue
Map<String, List<DocumentsChanges>> Map containing list of changes per document ID.

Example I

try (IDocumentSession session = store.openSession()) {
    Employee employee = new Employee();
    employee.setFirstName("Joe");
    employee.setLastName("Doe");
    session.store(employee);

    Map<String, List<DocumentsChanges>> changes = session.advanced().whatChanged();
    List<DocumentsChanges> employeeChanges = changes.get("employees/1-A");
    DocumentsChanges.ChangeType change
        = employeeChanges.get(0).getChange(); // DocumentsChanges.ChangeType.DOCUMENT_ADDED

}

Example II

try (IDocumentSession session = store.openSession()) {
    Employee employee = session.load(Employee.class, "employees/1-A");// 'Joe Doe'
    employee.setFirstName("John");
    employee.setLastName("Shmoe");

    Map<String, List<DocumentsChanges>> changes = session.advanced().whatChanged();
    List<DocumentsChanges> employeeChanges = changes.get("employees/1-A");
    DocumentsChanges change1
        = employeeChanges.get(0); //DocumentsChanges.ChangeType.FIELD_CHANGED
    DocumentsChanges change2
        = employeeChanges.get(1); //DocumentsChanges.ChangeType.FIELD_CHANGED
}