or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

exception-handling.mdhibernate-integration.mdindex.mdjpa-integration.mdpersistence-context.mdtransaction-management.md

hibernate-integration.mddocs/

0

# Hibernate Integration

1

2

Spring ORM provides native Hibernate 5.x integration with SessionFactory configuration, transaction management, template-based data access operations, exception translation, and comprehensive Spring lifecycle management. This integration offers both programmatic and declarative approaches to Hibernate usage within Spring applications.

3

4

## Capabilities

5

6

### SessionFactory Configuration

7

8

Configure Hibernate SessionFactory instances with Spring lifecycle management, automatic entity scanning, configuration file processing, and DataSource integration.

9

10

```java { .api }

11

public class LocalSessionFactoryBean extends HibernateExceptionTranslator

12

implements FactoryBean<SessionFactory>, ResourceLoaderAware, InitializingBean, DisposableBean {

13

public void setDataSource(DataSource dataSource);

14

public void setConfigLocation(Resource configLocation);

15

public void setConfigLocations(Resource... configLocations);

16

public void setMappingResources(String... mappingResources);

17

public void setMappingLocations(Resource... mappingLocations);

18

public void setCacheableMappingLocations(Resource... cacheableMappingLocations);

19

public void setMappingJarLocations(Resource... mappingJarLocations);

20

public void setMappingDirectoryLocations(Resource... mappingDirectoryLocations);

21

public void setAnnotatedClasses(Class<?>... annotatedClasses);

22

public void setAnnotatedPackages(String... annotatedPackages);

23

public void setPackagesToScan(String... packagesToScan);

24

public void setEntityTypeFilters(TypeFilter... entityTypeFilters);

25

public void setHibernateProperties(Properties hibernateProperties);

26

public Properties getHibernateProperties();

27

public void setEntityInterceptor(Interceptor entityInterceptor);

28

public void setPhysicalNamingStrategy(PhysicalNamingStrategy physicalNamingStrategy);

29

public void setImplicitNamingStrategy(ImplicitNamingStrategy implicitNamingStrategy);

30

public void setJtaTransactionManager(Object jtaTransactionManager);

31

public void setCacheRegionFactory(RegionFactory cacheRegionFactory);

32

public void setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider);

33

public void setCurrentTenantIdentifierResolver(CurrentTenantIdentifierResolver currentTenantIdentifierResolver);

34

public void setBootstrapExecutor(AsyncTaskExecutor bootstrapExecutor);

35

public void setHibernateIntegrators(Integrator... hibernateIntegrators);

36

public void setMetadataSources(MetadataSources metadataSources);

37

public MetadataSources getMetadataSources();

38

public Configuration getConfiguration();

39

40

public SessionFactory getObject();

41

public Class<?> getObjectType();

42

public boolean isSingleton();

43

public void afterPropertiesSet() throws IOException;

44

45

protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb);

46

}

47

48

public class LocalSessionFactoryBuilder {

49

public LocalSessionFactoryBuilder(DataSource dataSource);

50

public LocalSessionFactoryBuilder(DataSource dataSource, ClassLoader classLoader);

51

public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader);

52

public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader, MetadataSources metadataSources);

53

54

public LocalSessionFactoryBuilder setJtaTransactionManager(Object jtaTransactionManager);

55

public LocalSessionFactoryBuilder setBeanContainer(ConfigurableListableBeanFactory beanFactory);

56

public LocalSessionFactoryBuilder setCacheRegionFactory(RegionFactory cacheRegionFactory);

57

public LocalSessionFactoryBuilder setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider);

58

public LocalSessionFactoryBuilder setEntityTypeFilters(TypeFilter... entityTypeFilters);

59

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

60

public LocalSessionFactoryBuilder addPackages(String... annotatedPackages);

61

public LocalSessionFactoryBuilder scanPackages(String... packagesToScan) throws HibernateException;

62

63

public SessionFactory buildSessionFactory(AsyncTaskExecutor bootstrapExecutor);

64

}

65

```

66

67

#### Usage Example

68

69

```java

70

@Configuration

71

@EnableTransactionManagement

72

public class HibernateConfig {

73

74

@Bean

75

public LocalSessionFactoryBean sessionFactory() {

76

LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

77

sessionFactory.setDataSource(dataSource());

78

sessionFactory.setPackagesToScan("com.example.entity");

79

80

// Set Hibernate properties

81

Properties hibernateProperties = new Properties();

82

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

83

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

84

hibernateProperties.setProperty("hibernate.format_sql", "true");

85

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

86

hibernateProperties.setProperty("hibernate.jdbc.batch_size", "20");

87

hibernateProperties.setProperty("hibernate.order_inserts", "true");

88

hibernateProperties.setProperty("hibernate.order_updates", "true");

89

hibernateProperties.setProperty("hibernate.jdbc.batch_versioned_data", "true");

90

sessionFactory.setHibernateProperties(hibernateProperties);

91

92

// Optional: Set naming strategies

93

sessionFactory.setPhysicalNamingStrategy(new CamelCaseToUnderscoresNamingStrategy());

94

sessionFactory.setImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE);

95

96

// Optional: Set entity interceptor

97

sessionFactory.setEntityInterceptor(new AuditInterceptor());

98

99

return sessionFactory;

100

}

101

102

@Bean

103

public DataSource dataSource() {

104

HikariDataSource dataSource = new HikariDataSource();

105

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

106

dataSource.setUsername("user");

107

dataSource.setPassword("password");

108

return dataSource;

109

}

110

}

111

112

// Custom entity interceptor for auditing

113

public class AuditInterceptor implements Interceptor {

114

115

@Override

116

public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {

117

if (entity instanceof Auditable) {

118

Auditable auditable = (Auditable) entity;

119

auditable.setCreatedAt(Instant.now());

120

auditable.setUpdatedAt(Instant.now());

121

}

122

return false;

123

}

124

125

@Override

126

public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {

127

if (entity instanceof Auditable) {

128

Auditable auditable = (Auditable) entity;

129

auditable.setUpdatedAt(Instant.now());

130

}

131

return false;

132

}

133

}

134

```

135

136

### Hibernate Transaction Management

137

138

Dedicated transaction management for Hibernate with Session lifecycle integration, resource synchronization, and transaction-aware Session creation.

139

140

```java { .api }

141

public class HibernateTransactionManager extends AbstractPlatformTransactionManager

142

implements ResourceTransactionManager, BeanFactoryAware, InitializingBean {

143

public HibernateTransactionManager();

144

public HibernateTransactionManager(SessionFactory sessionFactory);

145

146

public void setSessionFactory(SessionFactory sessionFactory);

147

public SessionFactory getSessionFactory();

148

protected final SessionFactory obtainSessionFactory();

149

150

public void setDataSource(DataSource dataSource);

151

public DataSource getDataSource();

152

public void setAutodetectDataSource(boolean autodetectDataSource);

153

154

public void setPrepareConnection(boolean prepareConnection);

155

public void setHibernateManagedSession(boolean hibernateManagedSession);

156

157

public void setSessionInitializer(Consumer<Session> sessionInitializer);

158

public void setEntityInterceptorBeanName(String entityInterceptorBeanName);

159

public void setEntityInterceptor(Interceptor entityInterceptor);

160

public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException;

161

162

public Object getResourceFactory();

163

protected DataAccessException convertHibernateAccessException(HibernateException ex);

164

}

165

166

public class SessionHolder extends EntityManagerHolder {

167

public SessionHolder(Session session);

168

public Session getSession();

169

}

170

```

171

172

#### Usage Example

173

174

```java

175

@Configuration

176

@EnableTransactionManagement

177

public class TransactionConfig {

178

179

@Bean

180

public PlatformTransactionManager transactionManager(SessionFactory sessionFactory) {

181

HibernateTransactionManager txManager = new HibernateTransactionManager();

182

txManager.setSessionFactory(sessionFactory);

183

184

// Optional: Set DataSource for connection-level transaction synchronization

185

txManager.setDataSource(dataSource());

186

187

// Optional: Set Hibernate properties for transaction-scoped Sessions

188

Properties txProperties = new Properties();

189

txProperties.setProperty("hibernate.connection.isolation", "2"); // READ_COMMITTED

190

txManager.setHibernateProperties(txProperties);

191

192

return txManager;

193

}

194

}

195

196

@Service

197

@Transactional

198

public class ProductService {

199

200

@Autowired

201

private SessionFactory sessionFactory;

202

203

public void createProduct(String name, BigDecimal price) {

204

Session session = sessionFactory.getCurrentSession();

205

206

Product product = new Product();

207

product.setName(name);

208

product.setPrice(price);

209

product.setCreatedAt(Instant.now());

210

211

session.save(product);

212

// Transaction automatically commits on method completion

213

}

214

215

@Transactional(readOnly = true)

216

public List<Product> findProductsByPriceRange(BigDecimal minPrice, BigDecimal maxPrice) {

217

Session session = sessionFactory.getCurrentSession();

218

219

Query<Product> query = session.createQuery(

220

"FROM Product p WHERE p.price BETWEEN :minPrice AND :maxPrice",

221

Product.class

222

);

223

query.setParameter("minPrice", minPrice);

224

query.setParameter("maxPrice", maxPrice);

225

226

return query.getResultList();

227

}

228

}

229

```

230

231

### Hibernate Template Operations

232

233

Template-based approach for Hibernate operations with automatic Session management, exception translation, and common CRUD operations.

234

235

```java { .api }

236

public interface HibernateOperations {

237

<T> T execute(HibernateCallback<T> action) throws DataAccessException;

238

<T> T get(Class<T> entityClass, Serializable id) throws DataAccessException;

239

<T> T get(Class<T> entityClass, Serializable id, LockMode lockMode) throws DataAccessException;

240

Object get(String entityName, Serializable id) throws DataAccessException;

241

<T> T load(Class<T> entityClass, Serializable id) throws DataAccessException;

242

<T> List<T> loadAll(Class<T> entityClass) throws DataAccessException;

243

void load(Object entity, Serializable id) throws DataAccessException;

244

void refresh(Object entity) throws DataAccessException;

245

void refresh(Object entity, LockMode lockMode) throws DataAccessException;

246

boolean contains(Object entity) throws DataAccessException;

247

void evict(Object entity) throws DataAccessException;

248

void initialize(Object proxy) throws DataAccessException;

249

Filter enableFilter(String filterName) throws IllegalStateException, DataAccessException;

250

void lock(Object entity, LockMode lockMode) throws DataAccessException;

251

Serializable save(Object entity) throws DataAccessException;

252

void update(Object entity) throws DataAccessException;

253

void saveOrUpdate(Object entity) throws DataAccessException;

254

void replicate(Object entity, ReplicationMode replicationMode) throws DataAccessException;

255

void persist(Object entity) throws DataAccessException;

256

<T> T merge(T entity) throws DataAccessException;

257

void delete(Object entity) throws DataAccessException;

258

void deleteAll(Collection<?> entities) throws DataAccessException;

259

void flush() throws DataAccessException;

260

void clear() throws DataAccessException;

261

List<?> findByCriteria(DetachedCriteria criteria) throws DataAccessException;

262

<T> List<T> findByExample(T exampleEntity) throws DataAccessException;

263

}

264

265

public class HibernateTemplate implements HibernateOperations, InitializingBean {

266

public HibernateTemplate();

267

public HibernateTemplate(SessionFactory sessionFactory);

268

269

// Configuration methods

270

public void setSessionFactory(SessionFactory sessionFactory);

271

public SessionFactory getSessionFactory();

272

protected final SessionFactory obtainSessionFactory();

273

public void setFilterNames(String... filterNames);

274

public String[] getFilterNames();

275

public void setExposeNativeSession(boolean exposeNativeSession);

276

public boolean isExposeNativeSession();

277

public void setCheckWriteOperations(boolean checkWriteOperations);

278

public boolean isCheckWriteOperations();

279

public void setCacheQueries(boolean cacheQueries);

280

public boolean isCacheQueries();

281

public void setQueryCacheRegion(String queryCacheRegion);

282

public String getQueryCacheRegion();

283

public void setFetchSize(int fetchSize);

284

public int getFetchSize();

285

public void setMaxResults(int maxResults);

286

public int getMaxResults();

287

288

// Core template methods

289

public <T> T execute(HibernateCallback<T> action) throws DataAccessException;

290

public <T> T executeWithNativeSession(HibernateCallback<T> action);

291

292

// Load operations

293

public <T> T get(Class<T> entityClass, Serializable id) throws DataAccessException;

294

public <T> T get(Class<T> entityClass, Serializable id, LockMode lockMode) throws DataAccessException;

295

public Object get(String entityName, Serializable id) throws DataAccessException;

296

public <T> T load(Class<T> entityClass, Serializable id) throws DataAccessException;

297

public <T> List<T> loadAll(Class<T> entityClass) throws DataAccessException;

298

public void load(Object entity, Serializable id) throws DataAccessException;

299

public void refresh(Object entity) throws DataAccessException;

300

public boolean contains(Object entity) throws DataAccessException;

301

public void evict(Object entity) throws DataAccessException;

302

public void initialize(Object proxy) throws DataAccessException;

303

public Filter enableFilter(String filterName) throws IllegalStateException;

304

305

// Save/Update/Delete operations

306

public void lock(Object entity, LockMode lockMode) throws DataAccessException;

307

public Serializable save(Object entity) throws DataAccessException;

308

public void update(Object entity) throws DataAccessException;

309

public void saveOrUpdate(Object entity) throws DataAccessException;

310

public void replicate(Object entity, ReplicationMode replicationMode) throws DataAccessException;

311

public void persist(Object entity) throws DataAccessException;

312

public <T> T merge(T entity) throws DataAccessException;

313

public void delete(Object entity) throws DataAccessException;

314

public void deleteAll(Collection<?> entities) throws DataAccessException;

315

public void flush() throws DataAccessException;

316

public void clear() throws DataAccessException;

317

318

// Query operations

319

public List<?> findByCriteria(DetachedCriteria criteria) throws DataAccessException;

320

public <T> List<T> findByExample(T exampleEntity) throws DataAccessException;

321

}

322

323

public interface HibernateCallback<T> {

324

T doInHibernate(Session session) throws HibernateException;

325

}

326

```

327

328

#### Usage Example

329

330

```java

331

@Repository

332

public class CustomerRepository {

333

334

@Autowired

335

private HibernateTemplate hibernateTemplate;

336

337

// Basic CRUD operations

338

public void saveCustomer(Customer customer) {

339

hibernateTemplate.save(customer);

340

}

341

342

public Customer findCustomerById(Long id) {

343

return hibernateTemplate.get(Customer.class, id);

344

}

345

346

public void updateCustomer(Customer customer) {

347

hibernateTemplate.update(customer);

348

}

349

350

public void deleteCustomer(Customer customer) {

351

hibernateTemplate.delete(customer);

352

}

353

354

// Batch operations

355

public void saveAllCustomers(List<Customer> customers) {

356

hibernateTemplate.executeWithNativeSession(session -> {

357

for (int i = 0; i < customers.size(); i++) {

358

session.save(customers.get(i));

359

if (i % 20 == 0) {

360

session.flush();

361

session.clear();

362

}

363

}

364

return null;

365

});

366

}

367

368

// Complex queries using callback

369

public List<Customer> findCustomersWithOrders() {

370

return hibernateTemplate.execute(session -> {

371

Query<Customer> query = session.createQuery(

372

"SELECT DISTINCT c FROM Customer c JOIN FETCH c.orders",

373

Customer.class

374

);

375

return query.getResultList();

376

});

377

}

378

379

// Criteria-based queries

380

public List<Customer> findActiveCustomers() {

381

DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);

382

criteria.add(Restrictions.eq("active", true));

383

criteria.addOrder(Order.asc("lastName"));

384

385

@SuppressWarnings("unchecked")

386

List<Customer> customers = (List<Customer>) hibernateTemplate.findByCriteria(criteria);

387

return customers;

388

}

389

390

// Query by example

391

public List<Customer> findCustomersByExample(String city, String country) {

392

Customer example = new Customer();

393

example.setCity(city);

394

example.setCountry(country);

395

396

return hibernateTemplate.findByExample(example);

397

}

398

}

399

```

400

401

### Session Management Utilities

402

403

Helper utilities for obtaining transactional Session instances, managing Session lifecycle, and converting Hibernate exceptions.

404

405

```java { .api }

406

public abstract class SessionFactoryUtils {

407

public static final int SESSION_SYNCHRONIZATION_ORDER = DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 100;

408

409

public static void closeSession(Session session);

410

public static DataSource getDataSource(SessionFactory sessionFactory);

411

public static DataAccessException convertHibernateAccessException(HibernateException ex);

412

413

static void flush(Session session, boolean synch) throws DataAccessException;

414

}

415

416

public class SpringSessionContext implements CurrentSessionContext {

417

public Session currentSession() throws HibernateException;

418

}

419

420

public class SpringJtaSessionContext extends JTASessionContext {

421

// Spring-specific JTA session management

422

}

423

```

424

425

#### Usage Example

426

427

```java

428

@Component

429

public class CustomHibernateService {

430

431

@Autowired

432

private SessionFactory sessionFactory;

433

434

public void performCustomOperation() {

435

// In Spring Hibernate integration, use SessionFactory.getCurrentSession() in transactional context

436

try {

437

Session session = sessionFactory.getCurrentSession();

438

439

// Perform custom operations

440

Query<?> query = session.createQuery("FROM Product p WHERE p.discontinued = false");

441

List<?> products = query.getResultList();

442

443

// Process products...

444

445

} catch (HibernateException ex) {

446

DataAccessException dae = SessionFactoryUtils.convertHibernateAccessException(ex);

447

throw dae;

448

}

449

}

450

451

@Transactional

452

public void useCurrentSession() {

453

// In a transactional context, getCurrentSession() returns the transaction-bound session

454

Session session = sessionFactory.getCurrentSession();

455

456

// Session is automatically managed by Spring transaction manager

457

Product product = session.get(Product.class, 1L);

458

if (product != null) {

459

product.setLastAccessed(Instant.now());

460

session.update(product);

461

}

462

}

463

}

464

```

465

466

### Hibernate Exception Translation

467

468

Automatic translation of Hibernate exceptions to Spring's DataAccessException hierarchy for consistent error handling.

469

470

```java { .api }

471

public class HibernateExceptionTranslator implements PersistenceExceptionTranslator {

472

public DataAccessException translateExceptionIfPossible(RuntimeException ex);

473

}

474

475

// Hibernate-specific exceptions

476

public class HibernateJdbcException extends UncategorizedDataAccessException {

477

public HibernateJdbcException(JDBCException ex);

478

}

479

480

public class HibernateObjectRetrievalFailureException extends ObjectRetrievalFailureException {

481

public HibernateObjectRetrievalFailureException(ObjectNotFoundException ex);

482

public HibernateObjectRetrievalFailureException(UnresolvableObjectException ex);

483

}

484

485

public class HibernateOptimisticLockingFailureException extends ObjectOptimisticLockingFailureException {

486

public HibernateOptimisticLockingFailureException(StaleObjectStateException ex);

487

public HibernateOptimisticLockingFailureException(StaleStateException ex);

488

}

489

490

public class HibernateQueryException extends InvalidDataAccessResourceUsageException {

491

public HibernateQueryException(QueryException ex);

492

}

493

494

public class HibernateSystemException extends UncategorizedDataAccessException {

495

public HibernateSystemException(HibernateException ex);

496

}

497

```

498

499

### DAO Support Classes

500

501

Base classes providing convenient access to Hibernate functionality for Data Access Object implementations.

502

503

```java { .api }

504

public abstract class HibernateDaoSupport extends DaoSupport {

505

public void setSessionFactory(SessionFactory sessionFactory);

506

public SessionFactory getSessionFactory();

507

public void setHibernateTemplate(HibernateTemplate hibernateTemplate);

508

public HibernateTemplate getHibernateTemplate();

509

}

510

```

511

512

#### Usage Example

513

514

```java

515

@Repository

516

public class OrderDao extends HibernateDaoSupport {

517

518

// SessionFactory is automatically injected by Spring

519

@Autowired

520

public void setOrderSessionFactory(SessionFactory sessionFactory) {

521

setSessionFactory(sessionFactory);

522

}

523

524

public Order findOrderById(Long orderId) {

525

return getHibernateTemplate().get(Order.class, orderId);

526

}

527

528

public List<Order> findOrdersByCustomer(Long customerId) {

529

return getHibernateTemplate().execute(session -> {

530

Query<Order> query = session.createQuery(

531

"FROM Order o WHERE o.customer.id = :customerId ORDER BY o.orderDate DESC",

532

Order.class

533

);

534

query.setParameter("customerId", customerId);

535

return query.getResultList();

536

});

537

}

538

539

public void saveOrder(Order order) {

540

getHibernateTemplate().save(order);

541

}

542

543

public void updateOrder(Order order) {

544

getHibernateTemplate().update(order);

545

}

546

547

public void deleteOrder(Order order) {

548

getHibernateTemplate().delete(order);

549

}

550

}

551

```

552

553

### Spring Bean Container Integration

554

555

Hibernate BeanContainer implementation that integrates with Spring's BeanFactory for dependency injection in entity listeners and other Hibernate components.

556

557

```java { .api }

558

public class SpringBeanContainer implements BeanContainer {

559

// Provides integration between Hibernate and Spring's BeanFactory

560

// Allows Hibernate entity listeners and other components to receive dependency injection

561

}

562

563

public class ConfigurableJtaPlatform implements JtaPlatform {

564

// Configurable JTA platform implementation for Hibernate

565

// Allows custom configuration of transaction manager and user transaction

566

}

567

```

568

569

## Web Integration Support

570

571

Hibernate-specific web integration components for managing Sessions across HTTP requests.

572

573

```java { .api }

574

public class OpenSessionInViewFilter extends OncePerRequestFilter {

575

public static final String DEFAULT_SESSION_FACTORY_BEAN_NAME = "sessionFactory";

576

577

public void setSessionFactoryBeanName(String sessionFactoryBeanName);

578

public String getSessionFactoryBeanName();

579

public void setSingleSession(boolean singleSession);

580

}

581

582

public class OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor {

583

public static final String PARTICIPATE_SUFFIX = ".PARTICIPATE";

584

585

public void setSessionFactory(SessionFactory sessionFactory);

586

public SessionFactory getSessionFactory();

587

public void preHandle(WebRequest request) throws DataAccessException;

588

public void postHandle(WebRequest request, ModelMap model);

589

public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException;

590

}

591

592

public class OpenSessionInterceptor implements MethodInterceptor, InitializingBean {

593

// AOP-based session management for method-level session binding

594

}

595

```

596

597

#### Usage Example

598

599

```java

600

@Configuration

601

public class WebConfig implements WebMvcConfigurer {

602

603

@Autowired

604

private SessionFactory sessionFactory;

605

606

@Override

607

public void addInterceptors(InterceptorRegistry registry) {

608

OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();

609

interceptor.setSessionFactory(sessionFactory);

610

registry.addWebRequestInterceptor(interceptor);

611

}

612

}

613

614

// Or as a Servlet Filter

615

@WebFilter("/*")

616

public class CustomOpenSessionInViewFilter extends OpenSessionInViewFilter {

617

618

@Override

619

public void initFilterBean() {

620

setSessionFactoryBeanName("customSessionFactory");

621

setSingleSession(true); // Use single session per request

622

}

623

}

624

625

// AOP-based session management

626

@Configuration

627

@EnableAspectJAutoProxy

628

public class AopConfig {

629

630

@Bean

631

public OpenSessionInterceptor openSessionInterceptor() {

632

OpenSessionInterceptor interceptor = new OpenSessionInterceptor();

633

interceptor.setSessionFactory(sessionFactory);

634

return interceptor;

635

}

636

637

@Bean

638

public Advisor openSessionAdvisor() {

639

AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();

640

pointcut.setExpression("execution(* com.example.service.*.*(..))");

641

642

DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();

643

advisor.setPointcut(pointcut);

644

advisor.setAdvice(openSessionInterceptor());

645

646

return advisor;

647

}

648

}

649

```

650

651

### Transaction Synchronization

652

653

Advanced transaction synchronization support for proper resource cleanup and callback management.

654

655

```java { .api }

656

public class SpringSessionSynchronization implements TransactionSynchronization, Ordered {

657

public void beforeCommit(boolean readOnly);

658

public void beforeCompletion();

659

public void afterCommit();

660

public void afterCompletion(int status);

661

public int getOrder();

662

}

663

664

public class SpringFlushSynchronization implements TransactionSynchronization {

665

public void beforeCommit(boolean readOnly);

666

public void beforeCompletion();

667

public void afterCommit();

668

public void afterCompletion(int status);

669

}

670

```

671

672

## Types

673

674

```java { .api }

675

import org.hibernate.SessionFactory;

676

import org.hibernate.Session;

677

import org.hibernate.Query;

678

import org.hibernate.Criteria;

679

import org.hibernate.criterion.DetachedCriteria;

680

import org.hibernate.LockMode;

681

import org.hibernate.ReplicationMode;

682

import org.hibernate.Filter;

683

import org.hibernate.Interceptor;

684

import org.hibernate.HibernateException;

685

import org.hibernate.JDBCException;

686

import org.hibernate.ObjectNotFoundException;

687

import org.hibernate.QueryException;

688

import org.hibernate.StaleObjectStateException;

689

import org.hibernate.StaleStateException;

690

import org.hibernate.UnresolvableObjectException;

691

import org.hibernate.boot.model.naming.ImplicitNamingStrategy;

692

import org.hibernate.boot.model.naming.PhysicalNamingStrategy;

693

import org.hibernate.context.spi.CurrentSessionContext;

694

import org.hibernate.engine.spi.SessionFactoryImplementor;

695

import org.hibernate.resource.beans.container.spi.BeanContainer;

696

import org.hibernate.resource.transaction.spi.TransactionCoordinator;

697

import javax.sql.DataSource;

698

import java.io.Serializable;

699

import java.util.Collection;

700

import java.util.List;

701

import java.util.Properties;

702

import org.springframework.core.io.Resource;

703

import org.springframework.dao.DataAccessException;

704

import org.springframework.transaction.PlatformTransactionManager;

705

import org.springframework.web.context.request.WebRequest;

706

import org.springframework.ui.ModelMap;

707

```