Flow: JPA + Hibernate + Spring
Controller/Service
↓
Repository (Spring Data JPA) MyBatis Mapper
- auto sql - SQL in XML
↓ ↓
JPA EntityManager (JPA abstraction) JDBC
↓ ↓
Hibernate Session Database
↓
JDBC Connection
↓
Database
- EntityManager manages entity lifecycle (persist, merge, remove)
- Hibernate handles SQL, caching, lazy loading
- JDBC sends queries to DB
Setting in application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/testdb
username: root
password: pass
jpa:
hibernate:
ddl-auto: update
show-sql: true # prints each SQL queries to console
properties:
hibernate.format_sql: true # pretty-print SQL
JPA (Java Persistence API)
- Defines the standard specification for ORM in Java, but it is not an ORM tool itself. (not implementation)
- Defines how Java objects map to database tables
- Defines "what" to do, providing annotations like
@Entity and @Table.
- Works with multiple providers (Hibernate, EclipseLink, etc.)
Why JPA
- Avoid boilerplate JDBC code
- Maintain database independence