Using Hibernate directly requires manually managing SessionFactory, Sessions, and transactions. Each operation needs opening a session, beginning a transaction, performing the operation, committing or rolling back, and closing the session. This boilerplate leads to resource leaks and inconsistent transaction boundaries.
Spring ORM provides a consistent integration layer between Spring and ORM frameworks (Hibernate, JPA, MyBatis). It centralizes SessionFactory creation, provides automatic session management via HibernateTemplate, integrates with Spring’s transaction management, and translates Hibernate exceptions into Spring’s DataAccessException hierarchy.
- LocalSessionFactoryBean: Spring creates a Hibernate SessionFactory as a Spring bean, configuring it via Spring’s property management
- HibernateTransactionManager: Connects Hibernate’s transaction API to Spring’s platform transaction management — enables
@Transactionalon Hibernate operations - Session management: Spring opens and closes Hibernate Sessions automatically per operation (OpenSessionInView pattern)
- Exception translation:
@Repository+PersistenceExceptionTranslationPostProcessortranslates Hibernate exceptions to Spring’sDataAccessException - Automatic table creation: Hibernate’s
hibernate.hbm2ddl.autoproperty (create, update, validate) automatically generates DDL from entity mappings
- Centralized config: Hibernate properties (dialect, DDL auto, connection pool) configured in Spring, not hibernate.cfg.xml
- Automatic session: No session.open()/close() needed — Spring manages the lifecycle
- Transaction integration: Standard
@Transactionalworks with Hibernate operations - Exception translation: Vendor-specific exceptions → Spring’s unified DataAccessException hierarchy
- Automatic DDL:
hibernate.hbm2ddl.autogenerates database tables from entity classes - Lazy loading support: OpenSessionInViewFilter keeps session open during view rendering (controversial)
- Built from: Spring Framework — Spring ORM is a Spring module for ORM integration
- Built from: Hibernate ORM Framework — Spring ORM integrates Hibernate as the ORM provider
- Builds into: Spring Data JPA — Spring Data JPA uses Spring ORM under the hood for Hibernate integration
- Related: Spring JDBC Template — Both Spring ORM and JDBC Template are data access approaches in Spring
- Contrasts with: Container-Managed Persistence — CMP is EJB’s ORM; Spring ORM is more flexible and standalone
- OpenSessionInView anti-pattern: Keeping the session open during view rendering encourages lazy loading outside transactional boundaries, leading to N+1 queries hidden in views
- SessionFactory per data source: Multiple databases require separate SessionFactory beans
- Hibernate version conflicts: Spring Boot manages Hibernate version; manual dependency management can cause incompatibilities
- DDL auto in production: Never use
hibernate.hbm2ddl.auto=createorupdatein production — usevalidateor Flyway/Liquibase