Spring ORM is a module of the Spring Framework that integrates ORM frameworks like Hibernate, JPA, MyBatis, and EclipseLink. It reduces boilerplate code and ensures smooth interaction between Spring and persistence frameworks.
Features of Spring ORM
- Consistent API across ORM frameworks
- Transaction Management using @Transactional
- Exception Translation to DataAccessException
- Dependency Injection (IoC) support
- Automatic Session Management
ORM Frameworks Supported by Spring
Spring ORM supports multiple persistence technologies:
- JPA (Java Persistence API): A standard Java specification that defines APIs for mapping Java objects to relational database tables.
- Hibernate: A popular ORM framework that implements JPA and simplifies database operations using object-oriented concepts.
- MyBatis / iBATIS: A persistence framework that maps SQL queries directly to Java objects, giving developers full control over SQL.
- JDO (Java Data Objects): A Java specification for transparent persistence of Java objects to various data stores.
- Oracle TopLink: An enterprise-grade ORM and persistence framework (now EclipseLink) that provides advanced object–relational mapping features.
Core Components of Spring ORM
1. Template Classes
Template classes simplify common database operations such as save(), update(), delete(), and find(). Common templates include:
- HibernateTemplate
- JpaTemplate
- JdbcTemplate
Note: In modern applications, Spring Data JPA has largely replaced template-based APIs.
2. Transaction Management
Spring ORM provides both declarative and programmatic transaction management. Common Transaction Managers:
- HibernateTransactionManager
- JpaTransactionManager
- DataSourceTransactionManager
Example:
@Transactional
public void saveStudent(Student student) {
repository.save(student);
}
3. Session Management:
- Spring automatically manages Hibernate Session
- JPA uses EntityManager
- Prevents memory leaks and session mismanagement
4. Exception Translation:
Spring converts ORM-specific exceptions into a unified hierarchy:
- DataAccessException
This makes applications database-independent.
Hibernate vs Spring ORM
Aspect | Hibernate | Spring ORM |
|---|---|---|
Scope | ORM only | ORM + Transaction + DI |
Exception Handling | Hibernate-specific | Unified Spring exceptions |
Configuration | Manual | Simplified |
Integration | Standalone | Enterprise-ready |
