0
# Session Management
1
2
Core session and transaction management functionality in MyBatis. The SqlSession is the primary interface for all database operations, while SqlSessionFactory manages session creation and configuration.
3
4
## Capabilities
5
6
### SqlSessionFactory
7
8
Factory for creating SqlSession instances with various configuration options.
9
10
```java { .api }
11
/**
12
* Creates SqlSession instances from configuration or DataSource
13
*/
14
interface SqlSessionFactory {
15
/** Open session with default settings (no autocommit) */
16
SqlSession openSession();
17
18
/** Open session with autocommit setting */
19
SqlSession openSession(boolean autoCommit);
20
21
/** Open session with specific connection */
22
SqlSession openSession(Connection connection);
23
24
/** Open session with transaction isolation level */
25
SqlSession openSession(TransactionIsolationLevel level);
26
27
/** Open session with executor type */
28
SqlSession openSession(ExecutorType execType);
29
30
/** Open session with executor type and autocommit */
31
SqlSession openSession(ExecutorType execType, boolean autoCommit);
32
33
/** Open session with executor type and isolation level */
34
SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
35
36
/** Open session with executor type and connection */
37
SqlSession openSession(ExecutorType execType, Connection connection);
38
39
/** Get the configuration used by this factory */
40
Configuration getConfiguration();
41
}
42
```
43
44
**Usage Examples:**
45
46
```java
47
// Basic session creation
48
SqlSession session = sqlSessionFactory.openSession();
49
50
// Session with autocommit enabled
51
SqlSession autoCommitSession = sqlSessionFactory.openSession(true);
52
53
// Session with batch executor for bulk operations
54
SqlSession batchSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
55
56
// Session with specific isolation level
57
SqlSession isolatedSession = sqlSessionFactory.openSession(TransactionIsolationLevel.REPEATABLE_READ);
58
```
59
60
### SqlSessionFactoryBuilder
61
62
Builder for creating SqlSessionFactory instances from various configuration sources.
63
64
```java { .api }
65
/**
66
* Builder for SqlSessionFactory instances
67
*/
68
class SqlSessionFactoryBuilder {
69
/** Build from XML configuration file reader */
70
SqlSessionFactory build(Reader reader);
71
72
/** Build from XML with specific environment */
73
SqlSessionFactory build(Reader reader, String environment);
74
75
/** Build from XML with properties override */
76
SqlSessionFactory build(Reader reader, Properties properties);
77
78
/** Build from XML reader with environment and properties */
79
SqlSessionFactory build(Reader reader, String environment, Properties properties);
80
81
/** Build from XML configuration input stream */
82
SqlSessionFactory build(InputStream inputStream);
83
84
/** Build from input stream with specific environment */
85
SqlSessionFactory build(InputStream inputStream, String environment);
86
87
/** Build from input stream with properties override */
88
SqlSessionFactory build(InputStream inputStream, Properties properties);
89
90
/** Build from input stream with environment and properties */
91
SqlSessionFactory build(InputStream inputStream, String environment, Properties properties);
92
93
/** Build from pre-configured Configuration object */
94
SqlSessionFactory build(Configuration config);
95
}
96
```
97
98
**Usage Examples:**
99
100
```java
101
// Build from XML configuration file
102
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
103
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
104
105
// Build with specific environment (for multi-environment configs)
106
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
107
.build(inputStream, "production");
108
109
// Build with properties override
110
Properties props = new Properties();
111
props.setProperty("database.url", "jdbc:mysql://prod-server/db");
112
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
113
.build(inputStream, props);
114
```
115
116
### SqlSession
117
118
Primary interface for executing SQL statements and managing transactions.
119
120
```java { .api }
121
/**
122
* Primary interface for working with MyBatis. Execute commands, get mappers, manage transactions.
123
*/
124
interface SqlSession extends Closeable {
125
// Query operations
126
/** Retrieve single row mapped from statement key */
127
<T> T selectOne(String statement);
128
129
/** Retrieve single row with parameter */
130
<T> T selectOne(String statement, Object parameter);
131
132
/** Retrieve multiple rows */
133
<T> List<T> selectList(String statement);
134
135
/** Retrieve multiple rows with parameter */
136
<T> List<T> selectList(String statement, Object parameter);
137
138
/** Retrieve multiple rows with row bounds (pagination) */
139
<T> List<T> selectList(String statement, Object parameter, RowBounds rowBounds);
140
141
/** Retrieve cursor for large result sets */
142
<T> Cursor<T> selectCursor(String statement);
143
144
/** Retrieve cursor with parameter */
145
<T> Cursor<T> selectCursor(String statement, Object parameter);
146
147
/** Retrieve cursor with parameter and row bounds */
148
<T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds);
149
150
/** Stream results to custom handler */
151
void select(String statement, ResultHandler handler);
152
153
/** Stream results with parameter to custom handler */
154
void select(String statement, Object parameter, ResultHandler handler);
155
156
/** Stream results with parameter and row bounds to handler */
157
void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler);
158
159
// Update operations
160
/** Execute insert statement */
161
int insert(String statement);
162
163
/** Execute insert with parameter */
164
int insert(String statement, Object parameter);
165
166
/** Execute update statement */
167
int update(String statement);
168
169
/** Execute update with parameter */
170
int update(String statement, Object parameter);
171
172
/** Execute delete statement */
173
int delete(String statement);
174
175
/** Execute delete with parameter */
176
int delete(String statement, Object parameter);
177
178
// Transaction management
179
/** Commit current transaction */
180
void commit();
181
182
/** Commit transaction with force flag */
183
void commit(boolean force);
184
185
/** Rollback current transaction */
186
void rollback();
187
188
/** Rollback transaction with force flag */
189
void rollback(boolean force);
190
191
/** Flush batch statements and return results */
192
List<BatchResult> flushStatements();
193
194
/** Close the session */
195
void close();
196
197
/** Clear local session cache */
198
void clearCache();
199
200
// Mapper management
201
/** Get type-safe mapper interface implementation */
202
<T> T getMapper(Class<T> type);
203
204
// Connection and configuration access
205
/** Get underlying database connection */
206
Connection getConnection();
207
208
/** Get configuration used by this session */
209
Configuration getConfiguration();
210
}
211
```
212
213
**Usage Examples:**
214
215
```java
216
try (SqlSession session = sqlSessionFactory.openSession()) {
217
// Direct SQL execution with statement ID
218
User user = session.selectOne("com.example.UserMapper.selectById", 1);
219
List<User> users = session.selectList("com.example.UserMapper.selectAll");
220
221
// Insert with auto-generated key
222
User newUser = new User("John", "john@example.com");
223
session.insert("com.example.UserMapper.insert", newUser);
224
225
// Update and delete operations
226
user.setEmail("newemail@example.com");
227
session.update("com.example.UserMapper.update", user);
228
session.delete("com.example.UserMapper.delete", user.getId());
229
230
// Commit all changes
231
session.commit();
232
}
233
234
// Using mapper interfaces (type-safe approach)
235
try (SqlSession session = sqlSessionFactory.openSession()) {
236
UserMapper mapper = session.getMapper(UserMapper.class);
237
238
List<User> activeUsers = mapper.findByStatus("ACTIVE");
239
User user = mapper.findById(1);
240
241
mapper.updateEmail(user.getId(), "updated@example.com");
242
session.commit();
243
}
244
```
245
246
### Batch Operations
247
248
Efficient batch processing using BatchExecutor for bulk database operations.
249
250
```java { .api }
251
/**
252
* Result of batch operation execution
253
*/
254
class BatchResult {
255
/** Get the mapped statement that was executed */
256
MappedStatement getMappedStatement();
257
258
/** Get the SQL statement that was executed */
259
String getSql();
260
261
/** Get the parameter objects used in the batch */
262
List<Object> getParameterObjects();
263
264
/** Get the update counts for each statement in the batch */
265
int[] getUpdateCounts();
266
}
267
```
268
269
**Usage Examples:**
270
271
```java
272
// Batch operations for improved performance
273
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH)) {
274
UserMapper mapper = session.getMapper(UserMapper.class);
275
276
// Execute multiple operations in batch
277
for (User user : userList) {
278
mapper.insert(user);
279
}
280
281
// Flush batch and get results
282
List<BatchResult> results = session.flushStatements();
283
session.commit();
284
285
// Check batch results
286
for (BatchResult result : results) {
287
int[] updateCounts = result.getUpdateCounts();
288
System.out.println("Batch executed " + updateCounts.length + " statements");
289
}
290
}
291
```
292
293
### RowBounds and Pagination
294
295
Physical pagination support using RowBounds for limiting result sets.
296
297
```java { .api }
298
/**
299
* Physical row bounds for pagination
300
*/
301
class RowBounds {
302
/** Default row bounds (no limits) */
303
public static final RowBounds DEFAULT = new RowBounds();
304
305
/** Create row bounds with offset and limit */
306
public RowBounds(int offset, int limit);
307
308
/** Get the offset (starting row) */
309
public int getOffset();
310
311
/** Get the limit (max number of rows) */
312
public int getLimit();
313
}
314
```
315
316
**Usage Examples:**
317
318
```java
319
try (SqlSession session = sqlSessionFactory.openSession()) {
320
// Paginated query - get 10 records starting from record 20
321
RowBounds rowBounds = new RowBounds(20, 10);
322
List<User> users = session.selectList("selectAllUsers", null, rowBounds);
323
324
// Using with mapper interface
325
UserMapper mapper = session.getMapper(UserMapper.class);
326
List<User> pagedUsers = mapper.findAll(rowBounds);
327
}
328
```
329
330
## Types
331
332
```java { .api }
333
/**
334
* Executor types for different execution strategies
335
*/
336
enum ExecutorType {
337
/** Simple executor - creates new PreparedStatement for each execution */
338
SIMPLE,
339
340
/** Reuse executor - reuses PreparedStatements when SQL matches */
341
REUSE,
342
343
/** Batch executor - batches all updates until flushStatements() is called */
344
BATCH
345
}
346
347
/**
348
* Transaction isolation levels
349
*/
350
enum TransactionIsolationLevel {
351
NONE(Connection.TRANSACTION_NONE),
352
READ_UNCOMMITTED(Connection.TRANSACTION_READ_UNCOMMITTED),
353
READ_COMMITTED(Connection.TRANSACTION_READ_COMMITTED),
354
REPEATABLE_READ(Connection.TRANSACTION_REPEATABLE_READ),
355
SERIALIZABLE(Connection.TRANSACTION_SERIALIZABLE);
356
}
357
358
/**
359
* Custom result handler for streaming large result sets
360
*/
361
interface ResultHandler<T> {
362
/** Handle each result row */
363
void handleResult(ResultContext<? extends T> resultContext);
364
}
365
366
/**
367
* Context information for result handling
368
*/
369
interface ResultContext<T> {
370
/** Get the current result object */
371
T getResultObject();
372
373
/** Get the current result count */
374
int getResultCount();
375
376
/** Check if processing should stop */
377
boolean isStopped();
378
379
/** Stop the result processing */
380
void stop();
381
}
382
```