or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdentity-mapping.mdindex.mdqueries.mdsession-management.mdtransactions.mdtype-system.md

session-management.mddocs/

0

# Session Management

1

2

Session management in Hibernate Core provides the foundation for all persistence operations through the Session and SessionFactory interfaces. The Session represents a persistence context that manages entity instances and coordinates with the database.

3

4

## Capabilities

5

6

### Session Interface

7

8

The primary interface for persistence operations, representing a single unit of work and persistence context.

9

10

```java { .api }

11

/**

12

* Main runtime interface for persistence operations.

13

* Represents a single unit of work and persistence context.

14

*/

15

public interface Session extends SharedSessionContract, EntityManager, AutoCloseable {

16

// Entity lifecycle operations

17

18

/**

19

* Find an entity by primary key

20

* @param entityClass the entity type

21

* @param primaryKey the primary key value

22

* @return the entity instance or null if not found

23

*/

24

<T> T find(Class<T> entityClass, Object primaryKey);

25

26

/**

27

* Find an entity by primary key with lock mode

28

* @param entityClass the entity type

29

* @param primaryKey the primary key value

30

* @param lockMode the lock mode to use

31

* @return the entity instance or null if not found

32

*/

33

<T> T find(Class<T> entityClass, Object primaryKey, LockMode lockMode);

34

35

/**

36

* Make a persistent instance persistent

37

* @param entity the entity instance to persist

38

*/

39

void persist(Object entity);

40

41

/**

42

* Copy the state of the given object onto the persistent object

43

* @param entity the entity to merge

44

* @return the merged entity instance

45

*/

46

<T> T merge(T entity);

47

48

/**

49

* Remove a persistent instance from the datastore

50

* @param entity the entity instance to remove

51

*/

52

void remove(Object entity);

53

54

/**

55

* Re-read the state of the given instance from the underlying database

56

* @param entity the entity to refresh

57

*/

58

void refresh(Object entity);

59

60

/**

61

* Re-read the state of the given instance with the specified lock mode

62

* @param entity the entity to refresh

63

* @param lockMode the lock mode to use

64

*/

65

void refresh(Object entity, LockMode lockMode);

66

67

// Query creation methods

68

69

/**

70

* Create a Query instance for the given HQL/JPQL query string

71

* @param queryString the HQL/JPQL query string

72

* @param resultClass the expected result type

73

* @return Query instance

74

*/

75

<R> Query<R> createQuery(String queryString, Class<R> resultClass);

76

77

/**

78

* Create a Query instance for the given HQL/JPQL query string

79

* @param queryString the HQL/JPQL query string

80

* @return Query instance returning Object[]

81

*/

82

Query<Object[]> createQuery(String queryString);

83

84

/**

85

* Create a NativeQuery instance for the given native SQL query

86

* @param sqlString the native SQL query string

87

* @param resultClass the expected result type

88

* @return NativeQuery instance

89

*/

90

<R> NativeQuery<R> createNativeQuery(String sqlString, Class<R> resultClass);

91

92

/**

93

* Create a named query instance

94

* @param queryName the name of the query

95

* @param resultClass the expected result type

96

* @return Query instance

97

*/

98

<R> Query<R> createNamedQuery(String queryName, Class<R> resultClass);

99

100

// Transaction management

101

102

/**

103

* Begin a resource transaction

104

* @return the Transaction instance

105

*/

106

Transaction beginTransaction();

107

108

/**

109

* Get the current transaction

110

* @return the current Transaction instance

111

*/

112

Transaction getTransaction();

113

114

// Session state management

115

116

/**

117

* Force the Session to flush

118

*/

119

void flush();

120

121

/**

122

* Completely clear the session

123

*/

124

void clear();

125

126

/**

127

* Check if the session is still open

128

* @return true if session is open

129

*/

130

boolean isOpen();

131

132

/**

133

* Check if the session is connected

134

* @return true if session is connected

135

*/

136

boolean isConnected();

137

138

// Lock management

139

140

/**

141

* Obtain the specified lock level upon the given object

142

* @param entity the entity to lock

143

* @param lockMode the lock mode

144

*/

145

void lock(Object entity, LockMode lockMode);

146

147

/**

148

* Obtain the specified lock level upon the given object with timeout

149

* @param entity the entity to lock

150

* @param lockOptions lock options including mode and timeout

151

*/

152

void lock(Object entity, LockOptions lockOptions);

153

}

154

```

155

156

### SessionFactory Interface

157

158

Factory for creating Session instances and managing runtime metamodel.

159

160

```java { .api }

161

/**

162

* Factory for Session instances. Usually an application has a single SessionFactory.

163

* Thread-safe and intended to be shared by all application threads.

164

*/

165

public interface SessionFactory extends EntityManagerFactory, AutoCloseable {

166

/**

167

* Open a new Session

168

* @return the created Session

169

*/

170

Session openSession();

171

172

/**

173

* Get the current Session bound to the current context

174

* @return the current Session

175

* @throws HibernateException if no current session

176

*/

177

Session getCurrentSession();

178

179

/**

180

* Obtain a SessionBuilder for creating new sessions

181

* @return SessionBuilder instance

182

*/

183

SessionBuilder withOptions();

184

185

/**

186

* Execute work in a session, automatically managing the session lifecycle

187

* @param work the work to execute

188

* @return the result of the work

189

*/

190

<R> R inSession(Function<Session, R> work);

191

192

/**

193

* Execute work in a transaction, automatically managing session and transaction lifecycle

194

* @param work the work to execute

195

* @return the result of the work

196

*/

197

<R> R inTransaction(Function<Session, R> work);

198

199

// Metamodel and configuration access

200

201

/**

202

* Get the cache associated with this SessionFactory

203

* @return the Cache instance

204

*/

205

Cache getCache();

206

207

/**

208

* Get the statistics collector for this SessionFactory

209

* @return the Statistics instance

210

*/

211

Statistics getStatistics();

212

213

/**

214

* Check if the SessionFactory is closed

215

* @return true if closed

216

*/

217

boolean isClosed();

218

219

/**

220

* Close the SessionFactory and release resources

221

*/

222

void close();

223

}

224

```

225

226

### SessionBuilder Interface

227

228

Builder for creating customized Session instances.

229

230

```java { .api }

231

/**

232

* Builder for Session instances with custom configuration

233

*/

234

public interface SessionBuilder {

235

/**

236

* Open a session with the configured options

237

* @return the configured Session

238

*/

239

Session openSession();

240

241

/**

242

* Use the specified connection

243

* @param connection the JDBC connection to use

244

* @return this SessionBuilder for chaining

245

*/

246

SessionBuilder connection(Connection connection);

247

248

/**

249

* Use the specified connection release mode

250

* @param connectionReleaseMode the connection release mode

251

* @return this SessionBuilder for chaining

252

*/

253

SessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode);

254

255

/**

256

* Should the session built automatically close after completion of each transaction

257

* @param autoClose true to auto-close

258

* @return this SessionBuilder for chaining

259

*/

260

SessionBuilder autoClose(boolean autoClose);

261

262

/**

263

* Should the session be automatically flushed during completion of each transaction

264

* @param flushMode the flush mode to use

265

* @return this SessionBuilder for chaining

266

*/

267

SessionBuilder flushMode(FlushMode flushMode);

268

269

/**

270

* Specify the initial CacheMode for the session

271

* @param cacheMode the cache mode

272

* @return this SessionBuilder for chaining

273

*/

274

SessionBuilder cacheMode(CacheMode cacheMode);

275

}

276

```

277

278

### StatelessSession Interface

279

280

Session interface for bulk operations without persistence context.

281

282

```java { .api }

283

/**

284

* A stateless session interface for bulk operations.

285

* No persistence context, no first-level cache, no automatic dirty checking.

286

*/

287

public interface StatelessSession extends AutoCloseable {

288

/**

289

* Insert an entity

290

* @param entity the entity to insert

291

*/

292

void insert(Object entity);

293

294

/**

295

* Update an entity

296

* @param entity the entity to update

297

*/

298

void update(Object entity);

299

300

/**

301

* Delete an entity

302

* @param entity the entity to delete

303

*/

304

void delete(Object entity);

305

306

/**

307

* Retrieve an entity by id

308

* @param entityClass the entity type

309

* @param id the entity id

310

* @return the entity instance or null

311

*/

312

<T> T get(Class<T> entityClass, Object id);

313

314

/**

315

* Create a Query instance

316

* @param queryString the HQL/JPQL query string

317

* @param resultClass the expected result type

318

* @return Query instance

319

*/

320

<R> Query<R> createQuery(String queryString, Class<R> resultClass);

321

322

/**

323

* Create a native SQL query

324

* @param sqlString the native SQL query string

325

* @param resultClass the expected result type

326

* @return NativeQuery instance

327

*/

328

<R> NativeQuery<R> createNativeQuery(String sqlString, Class<R> resultClass);

329

330

/**

331

* Begin a transaction

332

* @return the Transaction instance

333

*/

334

Transaction beginTransaction();

335

336

/**

337

* Get the current transaction

338

* @return the current Transaction

339

*/

340

Transaction getTransaction();

341

342

/**

343

* Close the stateless session

344

*/

345

void close();

346

}

347

```

348

349

### SharedSessionContract

350

351

Base contract shared by Session and StatelessSession.

352

353

```java { .api }

354

/**

355

* Base contract for Session and StatelessSession

356

*/

357

public interface SharedSessionContract extends AutoCloseable {

358

/**

359

* Begin a resource transaction

360

* @return the Transaction instance

361

*/

362

Transaction beginTransaction();

363

364

/**

365

* Get the current transaction

366

* @return the current Transaction

367

*/

368

Transaction getTransaction();

369

370

/**

371

* Create a Query instance

372

* @param queryString the HQL/JPQL query string

373

* @return Query instance

374

*/

375

Query createQuery(String queryString);

376

377

/**

378

* Create a native SQL query

379

* @param sqlString the native SQL query string

380

* @return NativeQuery instance

381

*/

382

NativeQuery createNativeQuery(String sqlString);

383

384

/**

385

* Check if the session is open

386

* @return true if open

387

*/

388

boolean isOpen();

389

390

/**

391

* Check if the session is connected

392

* @return true if connected

393

*/

394

boolean isConnected();

395

396

/**

397

* Close the session

398

*/

399

void close();

400

}

401

```

402

403

## Usage Examples

404

405

### Basic Session Operations

406

407

```java

408

import org.hibernate.*;

409

410

// Opening and using a session

411

try (Session session = sessionFactory.openSession()) {

412

Transaction tx = session.beginTransaction();

413

414

// Create and persist an entity

415

User user = new User("john.doe", "John Doe");

416

session.persist(user);

417

418

// Find entity by ID

419

User foundUser = session.find(User.class, user.getId());

420

421

// Update entity

422

foundUser.setName("Jane Doe");

423

// No explicit save needed - automatic dirty checking

424

425

// Query entities

426

List<User> users = session.createQuery("FROM User u WHERE u.username LIKE :pattern", User.class)

427

.setParameter("pattern", "john%")

428

.getResultList();

429

430

tx.commit();

431

} // Session automatically closed

432

```

433

434

### Using SessionFactory Convenience Methods

435

436

```java

437

// Execute work in a session

438

List<User> users = sessionFactory.inSession(session ->

439

session.createQuery("FROM User", User.class).getResultList()

440

);

441

442

// Execute work in a transaction

443

User newUser = sessionFactory.inTransaction(session -> {

444

User user = new User("new.user", "New User");

445

session.persist(user);

446

return user;

447

});

448

```

449

450

### Stateless Session for Bulk Operations

451

452

```java

453

try (StatelessSession session = sessionFactory.openStatelessSession()) {

454

Transaction tx = session.beginTransaction();

455

456

// Bulk insert without persistence context overhead

457

for (int i = 0; i < 10000; i++) {

458

User user = new User("user" + i, "User " + i);

459

session.insert(user);

460

461

// Periodic flush for large batches

462

if (i % 100 == 0) {

463

session.getTransaction().commit();

464

session.beginTransaction();

465

}

466

}

467

468

tx.commit();

469

}

470

```

471

472

## Session State and Lifecycle

473

474

Sessions maintain entity state through several mechanisms:

475

476

- **Persistence Context**: First-level cache storing managed entity instances

477

- **Dirty Checking**: Automatic detection of entity changes for updates

478

- **Lazy Loading**: Transparent loading of associations and properties on access

479

- **Connection Management**: Automatic JDBC connection lifecycle management

480

- **Transaction Coordination**: Integration with local and JTA transactions