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 hasChanges and whatChanged methods are available in advanced session operations.

HasChanges

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

Syntax

public boolean hasChanges();

Example

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

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

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

WhatChanged

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

Syntax

public Map<String, List<DocumentsChanges>> whatChanged();
ReturnValue
Map<string, DocumentsChanges[]> Dictionary containing list of changes per document key.

Example I

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

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

Example II

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

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