or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdconnection-pooling.mdhibernate-integration.mdindex.mdjmx-management.mdmetrics-integration.mdutilities.md

hibernate-integration.mddocs/

0

# Hibernate Integration

1

2

Seamless integration with Hibernate ORM for connection provider implementation.

3

4

## Capabilities

5

6

### HikariConnectionProvider

7

8

Hibernate ConnectionProvider implementation using HikariCP for connection pooling.

9

10

```java { .api }

11

/**

12

* Hibernate ConnectionProvider implementation using HikariCP

13

* Integrates with Hibernate's connection management lifecycle

14

*/

15

public class HikariConnectionProvider

16

implements ConnectionProvider, Configurable, Stoppable, ServiceRegistryAwareService {

17

18

/**

19

* Get connection from HikariCP pool

20

* @return Connection from the pool

21

* @throws SQLException if connection cannot be obtained

22

*/

23

@Override

24

public Connection getConnection() throws SQLException;

25

26

/**

27

* Close/return connection to pool

28

* @param connection Connection to close

29

* @throws SQLException if error occurs during close

30

*/

31

@Override

32

public void closeConnection(Connection connection) throws SQLException;

33

34

/**

35

* Check if connection provider supports aggressive connection release

36

* @return true - HikariCP supports aggressive release

37

*/

38

@Override

39

public boolean supportsAggressiveRelease();

40

41

/**

42

* Check if connection provider is unwrappable

43

* @return false - HikariConnectionProvider is not unwrappable

44

*/

45

@Override

46

public boolean isUnwrappableAs(Class<?> unwrapType);

47

48

/**

49

* Unwrap connection provider (not supported)

50

* @throws UnknownUnwrapTypeException always thrown

51

*/

52

@Override

53

public <T> T unwrap(Class<T> unwrapType);

54

55

/**

56

* Configure the connection provider with Hibernate properties

57

* @param configurationValues Map of configuration properties

58

*/

59

@Override

60

public void configure(Map<String, Object> configurationValues);

61

62

/**

63

* Initialize the connection provider with service registry

64

* @param serviceRegistry Hibernate service registry

65

*/

66

@Override

67

public void injectServices(ServiceRegistryImplementor serviceRegistry);

68

69

/**

70

* Stop the connection provider and close HikariCP pool

71

*/

72

@Override

73

public void stop();

74

}

75

```

76

77

### HikariConfigurationUtil

78

79

Utility class for configuring HikariCP from Hibernate properties.

80

81

```java { .api }

82

/**

83

* Utility for converting Hibernate properties to HikariCP configuration

84

*/

85

public class HikariConfigurationUtil {

86

87

/**

88

* Load HikariCP configuration from Hibernate properties

89

* @param props Map of Hibernate configuration properties

90

* @return Configured HikariConfig instance

91

*/

92

public static HikariConfig loadConfiguration(Map<String, Object> props);

93

94

/**

95

* Copy Hibernate connection properties to HikariConfig

96

* @param hikariConfig Target HikariConfig instance

97

* @param props Source properties map

98

*/

99

public static void copyConfigurationValues(HikariConfig hikariConfig, Map<String, Object> props);

100

}

101

```

102

103

## Hibernate Configuration

104

105

### Using HikariConnectionProvider

106

107

Configure Hibernate to use HikariCP as the connection provider.

108

109

**hibernate.cfg.xml Configuration:**

110

111

```xml

112

<?xml version="1.0" encoding="utf-8"?>

113

<!DOCTYPE hibernate-configuration PUBLIC

114

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

115

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

116

117

<hibernate-configuration>

118

<session-factory>

119

<!-- Database connection settings -->

120

<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

121

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>

122

<property name="hibernate.connection.username">dbuser</property>

123

<property name="hibernate.connection.password">dbpass</property>

124

125

<!-- HikariCP connection provider -->

126

<property name="hibernate.connection.provider_class">com.zaxxer.hikari.hibernate.HikariConnectionProvider</property>

127

128

<!-- HikariCP-specific settings -->

129

<property name="hibernate.hikari.maximumPoolSize">20</property>

130

<property name="hibernate.hikari.minimumIdle">5</property>

131

<property name="hibernate.hikari.connectionTimeout">30000</property>

132

<property name="hibernate.hikari.idleTimeout">600000</property>

133

<property name="hibernate.hikari.maxLifetime">1800000</property>

134

<property name="hibernate.hikari.leakDetectionThreshold">60000</property>

135

136

<!-- DataSource properties -->

137

<property name="hibernate.hikari.dataSource.cachePrepStmts">true</property>

138

<property name="hibernate.hikari.dataSource.prepStmtCacheSize">250</property>

139

<property name="hibernate.hikari.dataSource.prepStmtCacheSqlLimit">2048</property>

140

141

<!-- Other Hibernate settings -->

142

<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

143

<property name="hibernate.show_sql">false</property>

144

<property name="hibernate.hbm2ddl.auto">validate</property>

145

</session-factory>

146

</hibernate-configuration>

147

```

148

149

**hibernate.properties Configuration:**

150

151

```properties

152

# Database connection

153

hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver

154

hibernate.connection.url=jdbc:mysql://localhost:3306/mydb

155

hibernate.connection.username=dbuser

156

hibernate.connection.password=dbpass

157

158

# HikariCP connection provider

159

hibernate.connection.provider_class=com.zaxxer.hikari.hibernate.HikariConnectionProvider

160

161

# HikariCP pool settings

162

hibernate.hikari.maximumPoolSize=20

163

hibernate.hikari.minimumIdle=5

164

hibernate.hikari.connectionTimeout=30000

165

hibernate.hikari.idleTimeout=600000

166

hibernate.hikari.maxLifetime=1800000

167

hibernate.hikari.poolName=Hibernate-Pool

168

hibernate.hikari.registerMbeans=true

169

170

# DataSource properties

171

hibernate.hikari.dataSource.cachePrepStmts=true

172

hibernate.hikari.dataSource.prepStmtCacheSize=250

173

hibernate.hikari.dataSource.useServerPrepStmts=true

174

175

# Hibernate settings

176

hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

177

hibernate.show_sql=false

178

hibernate.hbm2ddl.auto=validate

179

```

180

181

### Spring Boot Integration

182

183

Configure HikariCP with Hibernate in Spring Boot applications.

184

185

**application.yml:**

186

187

```yaml

188

spring:

189

datasource:

190

type: com.zaxxer.hikari.HikariDataSource

191

url: jdbc:mysql://localhost:3306/mydb

192

username: dbuser

193

password: dbpass

194

hikari:

195

maximum-pool-size: 20

196

minimum-idle: 5

197

connection-timeout: 30000

198

idle-timeout: 600000

199

max-lifetime: 1800000

200

pool-name: SpringBoot-Pool

201

register-mbeans: true

202

data-source-properties:

203

cachePrepStmts: true

204

prepStmtCacheSize: 250

205

prepStmtCacheSqlLimit: 2048

206

useServerPrepStmts: true

207

208

jpa:

209

hibernate:

210

ddl-auto: validate

211

properties:

212

hibernate:

213

dialect: org.hibernate.dialect.MySQL8Dialect

214

show_sql: false

215

```

216

217

**Java Configuration:**

218

219

```java

220

import com.zaxxer.hikari.HikariConfig;

221

import com.zaxxer.hikari.HikariDataSource;

222

import org.springframework.context.annotation.Bean;

223

import org.springframework.context.annotation.Configuration;

224

import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

225

226

@Configuration

227

public class HibernateConfig {

228

229

@Bean

230

public HikariDataSource dataSource() {

231

HikariConfig config = new HikariConfig();

232

config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");

233

config.setUsername("dbuser");

234

config.setPassword("dbpass");

235

config.setMaximumPoolSize(20);

236

config.setMinimumIdle(5);

237

config.setConnectionTimeout(30000);

238

config.setIdleTimeout(600000);

239

config.setMaxLifetime(1800000);

240

config.setPoolName("Spring-Hibernate-Pool");

241

config.setRegisterMbeans(true);

242

243

// MySQL optimizations

244

config.addDataSourceProperty("cachePrepStmts", "true");

245

config.addDataSourceProperty("prepStmtCacheSize", "250");

246

config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

247

config.addDataSourceProperty("useServerPrepStmts", "true");

248

249

return new HikariDataSource(config);

250

}

251

252

@Bean

253

public LocalSessionFactoryBean sessionFactory() {

254

LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

255

sessionFactory.setDataSource(dataSource());

256

sessionFactory.setPackagesToScan("com.myapp.entities");

257

258

Properties hibernateProperties = new Properties();

259

hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");

260

hibernateProperties.setProperty("hibernate.show_sql", "false");

261

hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "validate");

262

sessionFactory.setHibernateProperties(hibernateProperties);

263

264

return sessionFactory;

265

}

266

}

267

```

268

269

### Programmatic Configuration

270

271

Configure HikariCP with Hibernate programmatically.

272

273

```java

274

import org.hibernate.SessionFactory;

275

import org.hibernate.cfg.Configuration;

276

import com.zaxxer.hikari.HikariConfig;

277

import com.zaxxer.hikari.HikariDataSource;

278

279

public class HibernateUtil {

280

281

private static SessionFactory sessionFactory;

282

283

static {

284

try {

285

// Create HikariCP DataSource

286

HikariConfig hikariConfig = new HikariConfig();

287

hikariConfig.setJdbcUrl("jdbc:postgresql://localhost:5432/mydb");

288

hikariConfig.setUsername("dbuser");

289

hikariConfig.setPassword("dbpass");

290

hikariConfig.setMaximumPoolSize(15);

291

hikariConfig.setMinimumIdle(3);

292

hikariConfig.setConnectionTimeout(20000);

293

hikariConfig.setIdleTimeout(300000);

294

hikariConfig.setMaxLifetime(900000);

295

hikariConfig.setPoolName("Hibernate-Pool");

296

297

HikariDataSource dataSource = new HikariDataSource(hikariConfig);

298

299

// Configure Hibernate

300

Configuration configuration = new Configuration();

301

302

// Use HikariConnectionProvider

303

configuration.setProperty("hibernate.connection.provider_class",

304

"com.zaxxer.hikari.hibernate.HikariConnectionProvider");

305

306

// Set the DataSource

307

configuration.getProperties().put("hibernate.connection.datasource", dataSource);

308

309

// Other Hibernate properties

310

configuration.setProperty("hibernate.dialect",

311

"org.hibernate.dialect.PostgreSQL10Dialect");

312

configuration.setProperty("hibernate.show_sql", "false");

313

configuration.setProperty("hibernate.hbm2ddl.auto", "validate");

314

315

// Add annotated classes

316

configuration.addAnnotatedClass(User.class);

317

configuration.addAnnotatedClass(Order.class);

318

319

sessionFactory = configuration.buildSessionFactory();

320

321

} catch (Exception e) {

322

throw new ExceptionInInitializerError("Failed to create SessionFactory: " + e);

323

}

324

}

325

326

public static SessionFactory getSessionFactory() {

327

return sessionFactory;

328

}

329

330

public static void shutdown() {

331

if (sessionFactory != null) {

332

sessionFactory.close();

333

}

334

}

335

}

336

```

337

338

### Property Mapping

339

340

HikariCP properties can be configured through Hibernate with the `hibernate.hikari.` prefix.

341

342

**Core Properties:**

343

344

```properties

345

# Pool sizing

346

hibernate.hikari.maximumPoolSize=20

347

hibernate.hikari.minimumIdle=5

348

349

# Timeouts

350

hibernate.hikari.connectionTimeout=30000

351

hibernate.hikari.validationTimeout=5000

352

hibernate.hikari.idleTimeout=600000

353

hibernate.hikari.maxLifetime=1800000

354

hibernate.hikari.leakDetectionThreshold=60000

355

356

# Connection behavior

357

hibernate.hikari.autoCommit=true

358

hibernate.hikari.readOnly=false

359

hibernate.hikari.transactionIsolation=TRANSACTION_READ_COMMITTED

360

hibernate.hikari.catalog=mydb

361

hibernate.hikari.schema=public

362

363

# Pool management

364

hibernate.hikari.poolName=Hibernate-Pool

365

hibernate.hikari.registerMbeans=true

366

hibernate.hikari.allowPoolSuspension=false

367

368

# Connection testing

369

hibernate.hikari.connectionTestQuery=SELECT 1

370

hibernate.hikari.connectionInitSql=SET SESSION sql_mode = 'STRICT_TRANS_TABLES'

371

372

# DataSource properties (database-specific optimizations)

373

hibernate.hikari.dataSource.cachePrepStmts=true

374

hibernate.hikari.dataSource.prepStmtCacheSize=250

375

hibernate.hikari.dataSource.prepStmtCacheSqlLimit=2048

376

hibernate.hikari.dataSource.useServerPrepStmts=true

377

hibernate.hikari.dataSource.useLocalSessionState=true

378

hibernate.hikari.dataSource.rewriteBatchedStatements=true

379

```

380

381

### Usage Examples

382

383

Using Hibernate with HikariCP in different scenarios.

384

385

**Basic Hibernate Session Usage:**

386

387

```java

388

import org.hibernate.Session;

389

import org.hibernate.Transaction;

390

391

public class UserService {

392

393

public void saveUser(User user) {

394

Session session = HibernateUtil.getSessionFactory().openSession();

395

Transaction transaction = null;

396

397

try {

398

transaction = session.beginTransaction();

399

session.save(user);

400

transaction.commit();

401

} catch (Exception e) {

402

if (transaction != null) {

403

transaction.rollback();

404

}

405

throw e;

406

} finally {

407

session.close(); // Connection returned to HikariCP pool

408

}

409

}

410

411

public User findUser(Long id) {

412

try (Session session = HibernateUtil.getSessionFactory().openSession()) {

413

return session.get(User.class, id);

414

} // Connection automatically returned to pool

415

}

416

}

417

```

418

419

**Monitoring Hibernate + HikariCP:**

420

421

```java

422

import com.zaxxer.hikari.HikariDataSource;

423

import com.zaxxer.hikari.HikariPoolMXBean;

424

import org.hibernate.SessionFactory;

425

import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;

426

import org.hibernate.internal.SessionFactoryImpl;

427

428

public class HibernateMonitoring {

429

430

public void monitorConnectionPool(SessionFactory sessionFactory) {

431

if (sessionFactory instanceof SessionFactoryImpl) {

432

SessionFactoryImpl impl = (SessionFactoryImpl) sessionFactory;

433

ConnectionProvider provider = impl.getServiceRegistry()

434

.getService(ConnectionProvider.class);

435

436

if (provider instanceof HikariConnectionProvider) {

437

// Access HikariCP metrics through reflection or custom methods

438

// This requires implementation-specific access

439

System.out.println("Using HikariCP connection provider");

440

}

441

}

442

}

443

444

// Alternative: Monitor via JMX if registerMbeans=true

445

public void monitorViaJMX() {

446

try {

447

MBeanServer server = ManagementFactory.getPlatformMBeanServer();

448

ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (Hibernate-Pool)");

449

450

Integer active = (Integer) server.getAttribute(poolName, "ActiveConnections");

451

Integer idle = (Integer) server.getAttribute(poolName, "IdleConnections");

452

453

System.out.printf("Hibernate Pool - Active: %d, Idle: %d%n", active, idle);

454

} catch (Exception e) {

455

System.err.println("Failed to access JMX metrics: " + e.getMessage());

456

}

457

}

458

}