Session: Deleting entities

Entities can be marked for deletion by using delete method, but will not be removed from server until saveChanges is called.

Syntax

public <T> void delete(T entity);

public <T> void delete(Class<T> clazz, Number id);

public <T> void delete(Class<T> clazz, UUID id);

public void delete(String id);
Parameters
entity or id T, number, UUID or string instance of entity to delete or entity Id

Example 1

// if UseOptimisticConcurrency is set to 'true' (default 'false')
// this 'delete' method will use loaded 'employees/1' etag for concurrency check
// and might throw ConcurrencyException
Employee employee = session.load(Employee.class, "employees/1");
session.delete(employee);
session.saveChanges();

Example 2

// this 'Delete' method will not do any Etag-based concurrency checks
// because Etag for 'employees/1' is unknown
session.delete("employees/1");
session.saveChanges();

Information

If entity is not tracked by session, then executing

session.delete("employees/1");

is equal to doing

session.advanced().defer(new DeleteCommandData("employees/1", null));

You can read more about defer operations here.