Session: Opening a Session
To open session use the openSession
method from DocumentStore
.
Syntax
There are three overloads of openSession
methods
// Open session for a 'default' database configured in 'DocumentStore'
IDocumentSession openSession();
// Open session for a specified database
IDocumentSession openSession(String database);
IDocumentSession openSession(SessionOptions sessionOptions);
The first method is an equivalent of doing
store.openSession(new SessionOptions());
The second method is an equivalent of doing
SessionOptions sessionOptions = new SessionOptions();
sessionOptions.setDatabase(databaseName);
store.openSession(sessionOptions);
Parameters | ||
---|---|---|
options | OpenSessionOptions |
Options containing information such as name of database and RequestExecutor. |
Return Value | |
---|---|
IDocumentSession | Instance of a session object. |
Options
private String database;
private boolean noTracking;
private boolean noCaching;
private RequestExecutor requestExecutor;
private TransactionMode transactionMode;
// getters and setters
Options | ||
---|---|---|
database | String | Name of database that session should operate on. If null then default database set in DocumentStore is used. |
noTracking | boolean | Indicates if session should not keep track of the changes. Default: false . More here. |
noCaching | boolean | Indicates if session should not cache responses. Default: false . More here. |
requestExecutor | RequestExecutor |
(Advanced) Request executor to use. If null default one will be used. |
transactionMode | TransactionMode |
Sets the mode for the session. By default it is set to SINGLE_NODE , but session can also operate 'CLUSTER_WIDE'. You can read more about Cluster-Wide Transactions here. |
Example I
try (IDocumentSession session = store.openSession()) {
// code here
}
Example II - Disabling Entities Tracking
SessionOptions sessionOptions = new SessionOptions();
sessionOptions.setNoTracking(true);
try (IDocumentSession session = store.openSession()) {
Employee employee1 = session.load(Employee.class, "employees/1-A");
Employee employee2 = session.load(Employee.class, "employees/1-A");
// because NoTracking is set to 'true'
// each load will create a new Employee instance
Assert.assertNotSame(employee1, employee2);
}
Remarks
Important
Always remember to release session allocated resources after usage by invoking the close
method or wrapping the session object in the try
statement.