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

configuration.mddocs/

0

# Configuration and Bootstrap

1

2

Hibernate Core provides comprehensive configuration and bootstrap APIs for setting up the ORM framework, including metadata sources, service registries, and SessionFactory creation. The bootstrap process involves configuring mappings, database connections, and runtime behavior.

3

4

## Capabilities

5

6

### MetadataSources

7

8

Entry point for specifying entity mappings and configuration sources.

9

10

```java { .api }

11

/**

12

* Entry point for specifying sources of mapping metadata

13

*/

14

public class MetadataSources {

15

/**

16

* Create MetadataSources with the given service registry

17

* @param serviceRegistry the service registry to use

18

*/

19

public MetadataSources(ServiceRegistry serviceRegistry);

20

21

/**

22

* Add an annotated class as a source of mapping metadata

23

* @param annotatedClass the annotated entity class

24

* @return this MetadataSources for chaining

25

*/

26

public MetadataSources addAnnotatedClass(Class<?> annotatedClass);

27

28

/**

29

* Add multiple annotated classes

30

* @param annotatedClasses the annotated entity classes

31

* @return this MetadataSources for chaining

32

*/

33

public MetadataSources addAnnotatedClasses(Class<?>... annotatedClasses);

34

35

/**

36

* Add a package containing annotated classes

37

* @param packageName the package name to scan

38

* @return this MetadataSources for chaining

39

*/

40

public MetadataSources addPackage(String packageName);

41

42

/**

43

* Add a mapping resource (hbm.xml file)

44

* @param name the resource name/path

45

* @return this MetadataSources for chaining

46

*/

47

public MetadataSources addResource(String name);

48

49

/**

50

* Add a mapping file

51

* @param file the mapping file

52

* @return this MetadataSources for chaining

53

*/

54

public MetadataSources addFile(File file);

55

56

/**

57

* Add a JAR file containing mapping resources

58

* @param jar the JAR file

59

* @return this MetadataSources for chaining

60

*/

61

public MetadataSources addJar(File jar);

62

63

/**

64

* Get a MetadataBuilder for additional configuration

65

* @return MetadataBuilder instance

66

*/

67

public MetadataBuilder getMetadataBuilder();

68

69

/**

70

* Build the metadata with default settings

71

* @return the built Metadata

72

*/

73

public Metadata buildMetadata();

74

}

75

```

76

77

### MetadataBuilder

78

79

Builder for configuring metadata processing options.

80

81

```java { .api }

82

/**

83

* Builder for configuring metadata processing

84

*/

85

public interface MetadataBuilder {

86

/**

87

* Apply a naming strategy for database objects

88

* @param namingStrategy the naming strategy to use

89

* @return this MetadataBuilder for chaining

90

*/

91

MetadataBuilder applyNamingStrategy(NamingStrategy namingStrategy);

92

93

/**

94

* Apply basic type configurations

95

* @param typeContributor the type contributor

96

* @return this MetadataBuilder for chaining

97

*/

98

MetadataBuilder applyTypes(TypeContributor typeContributor);

99

100

/**

101

* Apply additional mapping information

102

* @param contributor the metadata contributor

103

* @return this MetadataBuilder for chaining

104

*/

105

MetadataBuilder applySources(MetadataSourcesContributor contributor);

106

107

/**

108

* Set the schema charset

109

* @param charset the charset to use

110

* @return this MetadataBuilder for chaining

111

*/

112

MetadataBuilder enableGlobalNationalizedCharacterDataSupport(boolean enabled);

113

114

/**

115

* Build the final Metadata instance

116

* @return the configured Metadata

117

*/

118

Metadata build();

119

}

120

```

121

122

### Metadata Interface

123

124

Container for mapping metadata and runtime metamodel information.

125

126

```java { .api }

127

/**

128

* Container for mapping metadata

129

*/

130

public interface Metadata {

131

/**

132

* Get a SessionFactoryBuilder for creating SessionFactory instances

133

* @return SessionFactoryBuilder instance

134

*/

135

SessionFactoryBuilder getSessionFactoryBuilder();

136

137

/**

138

* Build a SessionFactory with default settings

139

* @return the configured SessionFactory

140

*/

141

SessionFactory buildSessionFactory();

142

143

/**

144

* Get database metadata information

145

* @return Database metadata

146

*/

147

Database getDatabase();

148

149

/**

150

* Get all entity bindings

151

* @return collection of entity bindings

152

*/

153

Collection<PersistentClass> getEntityBindings();

154

155

/**

156

* Get entity binding by class

157

* @param entityClass the entity class

158

* @return the entity binding or null

159

*/

160

PersistentClass getEntityBinding(String entityName);

161

162

/**

163

* Get all collection bindings

164

* @return collection of collection bindings

165

*/

166

Collection<Collection> getCollectionBindings();

167

168

/**

169

* Get named query definitions

170

* @return map of named queries

171

*/

172

Map<String, NamedQueryDefinition> getNamedQueryDefinitions();

173

174

/**

175

* Get named native query definitions

176

* @return map of named native queries

177

*/

178

Map<String, NamedNativeQueryDefinition> getNamedNativeQueryDefinitions();

179

}

180

```

181

182

### SessionFactoryBuilder

183

184

Builder for creating and configuring SessionFactory instances.

185

186

```java { .api }

187

/**

188

* Builder for SessionFactory instances with additional configuration

189

*/

190

public interface SessionFactoryBuilder {

191

/**

192

* Apply additional SessionFactory configuration

193

* @param setting the setting name

194

* @param value the setting value

195

* @return this SessionFactoryBuilder for chaining

196

*/

197

SessionFactoryBuilder applySetting(String setting, Object value);

198

199

/**

200

* Apply multiple settings

201

* @param settings map of settings

202

* @return this SessionFactoryBuilder for chaining

203

*/

204

SessionFactoryBuilder applySettings(Map<String, Object> settings);

205

206

/**

207

* Add a SessionFactory observer

208

* @param observer the observer to add

209

* @return this SessionFactoryBuilder for chaining

210

*/

211

SessionFactoryBuilder addSessionFactoryObserver(SessionFactoryObserver observer);

212

213

/**

214

* Apply an interceptor

215

* @param interceptor the interceptor to apply

216

* @return this SessionFactoryBuilder for chaining

217

*/

218

SessionFactoryBuilder applyInterceptor(Interceptor interceptor);

219

220

/**

221

* Apply a statement inspector

222

* @param statementInspector the statement inspector

223

* @return this SessionFactoryBuilder for chaining

224

*/

225

SessionFactoryBuilder applyStatementInspector(StatementInspector statementInspector);

226

227

/**

228

* Enable/disable statistics collection

229

* @param enabled whether to enable statistics

230

* @return this SessionFactoryBuilder for chaining

231

*/

232

SessionFactoryBuilder applyStatisticsSupport(boolean enabled);

233

234

/**

235

* Build the configured SessionFactory

236

* @return the SessionFactory instance

237

*/

238

SessionFactory build();

239

}

240

```

241

242

### Configuration Settings

243

244

Core configuration interfaces defining available settings.

245

246

```java { .api }

247

/**

248

* Interface defining all available Hibernate configuration properties

249

*/

250

public interface AvailableSettings {

251

// Database connection settings

252

String JAKARTA_JDBC_DRIVER = "jakarta.persistence.jdbc.driver";

253

String JAKARTA_JDBC_URL = "jakarta.persistence.jdbc.url";

254

String JAKARTA_JDBC_USER = "jakarta.persistence.jdbc.user";

255

String JAKARTA_JDBC_PASSWORD = "jakarta.persistence.jdbc.password";

256

257

String DRIVER = "hibernate.connection.driver_class";

258

String URL = "hibernate.connection.url";

259

String USER = "hibernate.connection.username";

260

String PASS = "hibernate.connection.password";

261

262

// Connection pool settings

263

String POOL_SIZE = "hibernate.connection.pool_size";

264

String CONNECTION_PROVIDER = "hibernate.connection.provider_class";

265

266

// Database dialect

267

String DIALECT = "hibernate.dialect";

268

269

// Schema management

270

String HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";

271

String SHOW_SQL = "hibernate.show_sql";

272

String FORMAT_SQL = "hibernate.format_sql";

273

274

// Cache settings

275

String USE_SECOND_LEVEL_CACHE = "hibernate.cache.use_second_level_cache";

276

String USE_QUERY_CACHE = "hibernate.cache.use_query_cache";

277

String CACHE_REGION_FACTORY = "hibernate.cache.region.factory_class";

278

279

// Transaction settings

280

String TRANSACTION_COORDINATOR_STRATEGY = "hibernate.transaction.coordinator_class";

281

String JTA_PLATFORM = "hibernate.transaction.jta.platform";

282

}

283

284

/**

285

* JDBC-related configuration settings

286

*/

287

public interface JdbcSettings {

288

String STATEMENT_BATCH_SIZE = "hibernate.jdbc.batch_size";

289

String STATEMENT_FETCH_SIZE = "hibernate.jdbc.fetch_size";

290

String USE_SCROLLABLE_RESULTSET = "hibernate.jdbc.use_scrollable_resultset";

291

String USE_GET_GENERATED_KEYS = "hibernate.jdbc.use_get_generated_keys";

292

}

293

294

/**

295

* Cache-related configuration settings

296

*/

297

public interface CacheSettings {

298

String CACHE_REGION_FACTORY = "hibernate.cache.region.factory_class";

299

String DEFAULT_CACHE_CONCURRENCY_STRATEGY = "hibernate.cache.default_cache_concurrency_strategy";

300

String CACHE_KEYS_FACTORY = "hibernate.cache.keys_factory";

301

}

302

```

303

304

### Service Registry

305

306

Service registry for managing Hibernate services and dependencies.

307

308

```java { .api }

309

/**

310

* Service registry for managing Hibernate services

311

*/

312

public interface ServiceRegistry {

313

/**

314

* Get a service by type

315

* @param serviceRole the service type

316

* @return the service instance

317

*/

318

<R extends Service> R getService(Class<R> serviceRole);

319

320

/**

321

* Check if a service is available

322

* @param serviceRole the service type

323

* @return true if service is available

324

*/

325

<R extends Service> boolean requireService(Class<R> serviceRole);

326

}

327

328

/**

329

* Builder for creating service registries

330

*/

331

public class StandardServiceRegistryBuilder {

332

/**

333

* Create a new builder

334

*/

335

public StandardServiceRegistryBuilder();

336

337

/**

338

* Configure from hibernate.cfg.xml

339

* @return this builder for chaining

340

*/

341

public StandardServiceRegistryBuilder configure();

342

343

/**

344

* Configure from specified resource

345

* @param resourceName the configuration resource name

346

* @return this builder for chaining

347

*/

348

public StandardServiceRegistryBuilder configure(String resourceName);

349

350

/**

351

* Apply a setting

352

* @param settingName the setting name

353

* @param value the setting value

354

* @return this builder for chaining

355

*/

356

public StandardServiceRegistryBuilder applySetting(String settingName, Object value);

357

358

/**

359

* Apply multiple settings

360

* @param settings the settings map

361

* @return this builder for chaining

362

*/

363

public StandardServiceRegistryBuilder applySettings(Map<String, Object> settings);

364

365

/**

366

* Build the service registry

367

* @return the configured service registry

368

*/

369

public StandardServiceRegistry build();

370

}

371

```

372

373

### Connection and JDBC Access

374

375

Hibernate provides access to the underlying JDBC connection for advanced scenarios.

376

377

```java { .api }

378

/**

379

* Access to the underlying JDBC connection

380

*/

381

public interface SessionImplementor extends Session, SharedSessionContractImplementor {

382

/**

383

* Get the JDBC connection

384

* @return the underlying JDBC Connection

385

*/

386

Connection connection();

387

388

/**

389

* Disconnect from the current JDBC connection

390

*/

391

void disconnect();

392

393

/**

394

* Reconnect to a JDBC connection

395

* @param connection the JDBC connection to use

396

*/

397

void reconnect(Connection connection);

398

399

/**

400

* Check if currently connected to a JDBC connection

401

* @return true if connected

402

*/

403

boolean isConnected();

404

}

405

406

/**

407

* JDBC connection management

408

*/

409

public interface ConnectionProvider extends Service, Wrapped {

410

/**

411

* Obtain a connection from the underlying datasource

412

* @return the obtained connection

413

* @throws SQLException if unable to obtain connection

414

*/

415

Connection getConnection() throws SQLException;

416

417

/**

418

* Release a connection back to the underlying datasource

419

* @param connection the connection to release

420

* @throws SQLException if unable to release connection

421

*/

422

void closeConnection(Connection connection) throws SQLException;

423

424

/**

425

* Does this connection provider support aggressive release of JDBC connections

426

* @return true if aggressive release is supported

427

*/

428

boolean supportsAggressiveRelease();

429

}

430

431

/**

432

* JDBC work interface for executing work using raw JDBC

433

*/

434

public interface Work {

435

/**

436

* Execute work using the provided connection

437

* @param connection the JDBC connection to use

438

* @throws SQLException if SQL operations fail

439

*/

440

void execute(Connection connection) throws SQLException;

441

}

442

443

/**

444

* JDBC work interface that returns a result

445

* @param <T> the result type

446

*/

447

public interface ReturningWork<T> {

448

/**

449

* Execute work using the provided connection and return result

450

* @param connection the JDBC connection to use

451

* @return the result of the work

452

* @throws SQLException if SQL operations fail

453

*/

454

T execute(Connection connection) throws SQLException;

455

}

456

```

457

458

## Usage Examples

459

460

### Basic Bootstrap Configuration

461

462

```java

463

import org.hibernate.boot.MetadataSources;

464

import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

465

466

// Create service registry

467

StandardServiceRegistry registry = new StandardServiceRegistryBuilder()

468

.configure() // Loads from hibernate.cfg.xml

469

.build();

470

471

try {

472

// Create metadata sources and add entity classes

473

MetadataSources sources = new MetadataSources(registry)

474

.addAnnotatedClass(User.class)

475

.addAnnotatedClass(Order.class)

476

.addAnnotatedClass(Product.class);

477

478

// Build metadata and SessionFactory

479

Metadata metadata = sources.buildMetadata();

480

SessionFactory sessionFactory = metadata.buildSessionFactory();

481

482

// Use the SessionFactory...

483

484

} finally {

485

StandardServiceRegistryBuilder.destroy(registry);

486

}

487

```

488

489

### Programmatic Configuration

490

491

```java

492

import org.hibernate.boot.MetadataSources;

493

import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

494

import org.hibernate.cfg.AvailableSettings;

495

496

// Configure programmatically

497

StandardServiceRegistry registry = new StandardServiceRegistryBuilder()

498

.applySetting(AvailableSettings.DRIVER, "org.h2.Driver")

499

.applySetting(AvailableSettings.URL, "jdbc:h2:mem:testdb")

500

.applySetting(AvailableSettings.USER, "sa")

501

.applySetting(AvailableSettings.PASS, "")

502

.applySetting(AvailableSettings.DIALECT, "org.hibernate.dialect.H2Dialect")

503

.applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop")

504

.applySetting(AvailableSettings.SHOW_SQL, true)

505

.applySetting(AvailableSettings.FORMAT_SQL, true)

506

.build();

507

508

SessionFactory sessionFactory = new MetadataSources(registry)

509

.addAnnotatedClass(User.class)

510

.buildMetadata()

511

.buildSessionFactory();

512

```

513

514

### Advanced Configuration with Custom Components

515

516

```java

517

// Create metadata with custom configuration

518

MetadataBuilder metadataBuilder = new MetadataSources(registry)

519

.addAnnotatedClass(User.class)

520

.getMetadataBuilder();

521

522

// Apply custom naming strategy

523

metadataBuilder.applyNamingStrategy(new CustomNamingStrategy());

524

525

// Build metadata and SessionFactory with additional options

526

Metadata metadata = metadataBuilder.build();

527

SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()

528

.applyInterceptor(new AuditInterceptor())

529

.applyStatisticsSupport(true)

530

.addSessionFactoryObserver(new CustomSessionFactoryObserver())

531

.build();

532

```

533

534

### Configuration from Properties

535

536

```java

537

Properties props = new Properties();

538

props.setProperty(AvailableSettings.DRIVER, "com.mysql.cj.jdbc.Driver");

539

props.setProperty(AvailableSettings.URL, "jdbc:mysql://localhost:3306/mydb");

540

props.setProperty(AvailableSettings.USER, "username");

541

props.setProperty(AvailableSettings.PASS, "password");

542

props.setProperty(AvailableSettings.DIALECT, "org.hibernate.dialect.MySQLDialect");

543

props.setProperty(AvailableSettings.HBM2DDL_AUTO, "validate");

544

545

StandardServiceRegistry registry = new StandardServiceRegistryBuilder()

546

.applySettings(props)

547

.build();

548

549

SessionFactory sessionFactory = new MetadataSources(registry)

550

.addPackage("com.example.entities")

551

.buildMetadata()

552

.buildSessionFactory();

553

```

554

555

## Configuration Best Practices

556

557

### Resource Management

558

559

Always properly close resources to avoid memory leaks:

560

561

```java

562

StandardServiceRegistry registry = null;

563

SessionFactory sessionFactory = null;

564

565

try {

566

registry = new StandardServiceRegistryBuilder().configure().build();

567

sessionFactory = new MetadataSources(registry)

568

.addAnnotatedClass(User.class)

569

.buildMetadata()

570

.buildSessionFactory();

571

572

// Use SessionFactory...

573

574

} finally {

575

if (sessionFactory != null) {

576

sessionFactory.close();

577

}

578

if (registry != null) {

579

StandardServiceRegistryBuilder.destroy(registry);

580

}

581

}

582

```

583

584

### Environment-Specific Configuration

585

586

Use different configuration files for different environments:

587

588

```java

589

// Development

590

StandardServiceRegistry devRegistry = new StandardServiceRegistryBuilder()

591

.configure("hibernate-dev.cfg.xml")

592

.build();

593

594

// Production

595

StandardServiceRegistry prodRegistry = new StandardServiceRegistryBuilder()

596

.configure("hibernate-prod.cfg.xml")

597

.build();

598

```

599

600

### Direct JDBC Access

601

602

```java

603

// Execute raw JDBC work

604

session.doWork(connection -> {

605

try (PreparedStatement stmt = connection.prepareStatement(

606

"UPDATE users SET last_access = ? WHERE user_id = ?")) {

607

stmt.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now()));

608

stmt.setLong(2, userId);

609

stmt.executeUpdate();

610

}

611

});

612

613

// Execute JDBC work that returns a result

614

Integer count = session.doReturningWork(connection -> {

615

try (PreparedStatement stmt = connection.prepareStatement(

616

"SELECT COUNT(*) FROM orders WHERE status = 'ACTIVE'");

617

ResultSet rs = stmt.executeQuery()) {

618

if (rs.next()) {

619

return rs.getInt(1);

620

}

621

return 0;

622

}

623

});

624

625

// Access underlying JDBC connection (advanced usage)

626

SessionImplementor sessionImpl = (SessionImplementor) session;

627

Connection connection = sessionImpl.connection();

628

// Perform direct JDBC operations...

629

```