JPA Part 2 — Repositories
JpaRepository, CrudRepository, PagingAndSortingRepository, query derivation and Pageable
- Perform CRUD operations with JpaRepository
- Derive queries from method names (findByNameAndEmail)
- Paginate and sort results with Pageable and Sort
Series:
Concept and Coding — JPA Series Part: 2 of 3 Prerequisites: Spring Boot JDBC (Part 1)
Table of Contents
- ORM — Object Relational Mapping
- JPA vs Hibernate — Interface vs Implementation
- Minimal JPA Setup — The Four Steps
- JPA Architecture — Deep Dive
- Entity Lifecycle Inside Persistence Context
- JPA Repository vs Entity Manager — Why Use JPA Repository?
- First Level Caching (Introduction)
- Multi-DB Setup — Manual Configuration
- Common Mistakes & Best Practices
- Interview Notes
- Practice Questions
- Summary
1. ORM Object Relational Mapping
Overview
In the JDBC approach (Part 1), your application code directly connects to the database through JDBC and you write raw SQL queries. You are responsible for every PreparedStatement, ResultSet, and connection management call.
ORM (Object Relational Mapping) is a programming technique that inserts a framework layer between your Java application logic and the underlying JDBC layer. Instead of writing SQL, you interact with the database using plain Java objects.
1┌────────────────────┐2│ Application Logic │3└────────┬───────────┘4 │ works with Java Objects5┌────────▼───────────┐6│ ORM Framework │ ← NEW LAYER (JPA + Hibernate)7│ (JPA / Hibernate) │8└────────┬───────────┘9 │ generates and executes SQL10┌────────▼───────────┐11│ JDBC │12└────────┬───────────┘13 │14┌────────▼───────────┐15│ Database │16└────────────────────┘Why ORM Exists
| Problem with JDBC | How ORM Solves It |
|---|---|
| Must write raw SQL for every operation | Interact with DB using Java objects |
Must manually map ResultSet columns to Java fields | Automatic mapping via annotations |
| Boilerplate code for every CRUD operation | Pre-built CRUD methods via repositories |
| No object-level caching | First-level cache (Persistence Context) |
| Transaction management is manual | Automatic transaction management |
2. JPA vs Hibernate Interface vs Implementation
Definition
- JPA (Java Persistence API) is a specification — a set of interfaces and rules defined by the Java EE standard. It does not contain any actual implementation logic. Think of it as a contract.
- Hibernate, OpenJPA, and EclipseLink are implementations of JPA. They provide the actual code that fulfills the JPA contract.
Spring Boot Default
Spring Boot automatically uses Hibernate as the JPA implementation. When you add the spring-boot-starter-data-jpa dependency, Hibernate is pulled in transitively — you do not need to add Hibernate separately.
If you want to override this with a different provider:
1spring.jpa.properties.javax.persistence.provider=org.eclipse.persistence.jpa.PersistenceProvider3. Minimal JPA Setup The Four Steps
To get a basic JPA application running in Spring Boot, you need exactly four things:
Step 1 Add the JPA Dependency (`pom.xml`)
1<dependency>2 <groupId>org.springframework.boot</groupId>3 <artifactId>spring-boot-starter-data-jpa</artifactId>4</dependency>5
6<!-- Choose your database driver -->7<dependency>8 <groupId>com.h2database</groupId>9 <artifactId>h2</artifactId>10 <scope>runtime</scope>11</dependency>spring-boot-starter-data-jpa automatically brings in the Hibernate dependency. You do not need to add it separately.Step 2 Database Connection Properties (`application.properties`)
1# Data source configuration2spring.datasource.url=jdbc:h2:mem:userdb3spring.datasource.driver-class-name=org.h2.Driver4spring.datasource.username=sa5spring.datasource.password=6
7# H2 in-memory console (for development only)8spring.h2.console.enabled=true9spring.h2.console.path=/h2-console10
11# Show generated SQL in logs (development only)12spring.jpa.show-sql=true13spring.jpa.properties.hibernate.format_sql=truespring.jpa.show-sql=true and hibernate.format_sql=true are for development and debugging only. Never use them in production — they degrade performance and may expose sensitive data in logs.Step 3 Create an Entity Class
An Entity is a Java class that maps directly to a database table.
1import jakarta.persistence.*;2
3@Entity // Marks this class as a JPA entity (= a table)4@Table(name = "user_details") // Optional: explicitly name the table5public class UserDetails {6
7 @Id // Marks this field as the primary key8 @GeneratedValue(strategy = GenerationType.IDENTITY) // Auto-increment9 private Long id;10
11 private String name;12 private String email;13
14 // MANDATORY: JPA requires a no-arg constructor15 public UserDetails() {}16
17 // Getters and Setters (standard POJO)18 public Long getId() { return id; }19 public void setId(Long id) { this.id = id; }20
21 public String getName() { return name; }22 public void setName(String name) { this.name = name; }23
24 public String getEmail() { return email; }25 public void setEmail(String email) { this.email = email; }26}◆ Mapping Rules
| Java Concept | Database Concept |
|---|---|
@Entity class | Table |
| Class name (default) | Table name |
| Field | Column |
| Field name (default) | Column name |
new UserDetails() | A new row |
@Id field | Primary key column |
Step 4 Create a Repository Interface
1import org.springframework.data.jpa.repository.JpaRepository;2import org.springframework.stereotype.Repository;3
4@Repository5public interface UserDetailRepository extends JpaRepository<UserDetails, Long> {6 // JpaRepository<EntityType, PrimaryKeyType>7 // Pre-built methods available: save(), findAll(), findById(), deleteById(), count(), etc.8 9 // You can add custom queries here when needed:10 // List<UserDetails> findByName(String name);11}◆ Why a Separate Repository Per Entity?
- Each repository is tailored to one entity, keeping concerns separated.
- Custom JPQL (Java Persistence Query Language) or native SQL queries for that entity live here.
- Type safety is enforced via generics:
JpaRepositorymeans this repo works only withUserDetailsand itsLongprimary key.
Putting It All Together Controller Service Repository Flow
1// Controller2@RestController3@RequestMapping("/api")4public class UserController {5
6 @Autowired7 private UserService userService;8
9 @GetMapping("/test-jpa")10 public UserDetails testJpa() {11 userService.saveUser();12 return userService.getUser(1L);13 }14}15
16// Service17@Service18public class UserService {19
20 @Autowired21 private UserDetailRepository userDetailRepository;22
23 public void saveUser() {24 UserDetails user = new UserDetails();25 user.setName("XYZ");26 user.setEmail("xyz@conceptcoding.com");27 userDetailRepository.save(user); // Internally calls EntityManager.persist()28 }29
30 public UserDetails getUser(Long id) {31 return userDetailRepository.findById(id).orElse(null); // Internally: EntityManager.find()32 }33}◆ Layered Architecture
1HTTP Request2 │3 ▼4Controller ← handles HTTP, delegates to Service5 │6 ▼7Service ← business logic, calls Repository8 │9 ▼10Repository ← data access, wraps EntityManager11 │12 ▼13Database4. JPA Architecture Deep Dive
Once the basic flow is understood, it is critical to know what happens internally — what components exist, how they are created, and how they interact.
Architecture Overview
4.1 Persistence Unit
◆ What Is It?
A Persistence Unit is a named configuration block that groups:
- Which entities belong together (share the same database)
- Database connection details (URL, driver, username, password)
- JPA provider (Hibernate, EclipseLink, etc.)
- Dialect
- Transaction type
Think of it as a configuration profile for one database.
◆ In Plain Spring Boot (single DB)
You define it implicitly through application.properties. Spring Boot reads these properties and constructs a single Persistence Unit automatically.
◆ Without Spring Boot `persistence.xml`
If you are not using Spring Boot, or if you need multiple databases, you create a persistence.xml file inside src/main/resources/META-INF/:
1<persistence xmlns="https://jakarta.ee/xml/ns/persistence" version="3.0">2
3 <!-- Persistence Unit for H2 (in-memory) -->4 <persistence-unit name="h2-unit" transaction-type="RESOURCE_LOCAL">5 6 <!-- Entities belonging to this unit -->7 <class>com.example.SampleEntityOne</class>8 <class>com.example.SampleEntityTwo</class>9
10 <!-- JPA Provider -->11 <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>12
13 <properties>14 <property name="jakarta.persistence.jdbc.driver" value="org.h2.Driver"/>15 <property name="jakarta.persistence.jdbc.url" value="jdbc:h2:mem:userdb"/>16 <property name="jakarta.persistence.jdbc.user" value="sa"/>17 <property name="jakarta.persistence.jdbc.password" value=""/>18 <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>19 </properties>20 </persistence-unit>21
22 <!-- Separate Persistence Unit for MySQL -->23 <persistence-unit name="mysql-unit" transaction-type="RESOURCE_LOCAL">24 <class>com.example.OrderDetails</class>25 <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>26 <properties>27 <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>28 <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/orders"/>29 <property name="jakarta.persistence.jdbc.user" value="root"/>30 <property name="jakarta.persistence.jdbc.password" value="secret"/>31 <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>32 </properties>33 </persistence-unit>34
35</persistence>◆ Transaction Types
| Type | Scope | Use Case |
|---|---|---|
RESOURCE_LOCAL | Single database only | Standard Spring Boot apps |
JTA | Spans multiple databases | Distributed transactions, microservices with shared DBs |
application.properties in Spring Boot, you can only configure one database (one persistence unit). For multiple databases, use @Configuration classes.application.properties, Spring Boot defaults the transaction type to RESOURCE_LOCAL automatically. You do not need to specify it.4.2 Entity Manager Factory
◆ What Is It?
EntityManagerFactory is a Java object (created once, at application startup) that:
- Reads the Persistence Unit configuration
- Holds all JPA/Hibernate configuration in memory
- Acts as a factory — its sole purpose is to create
EntityManagerinstances on demand
◆ Relationship: Persistence Unit EntityManagerFactory
1One Persistence Unit → One EntityManagerFactory2
3H2 Persistence Unit → EntityManagerFactory for H24MySQL Persistence Unit → EntityManagerFactory for MySQLEntityManagerFactory is expensive to create and is a singleton per Persistence Unit. It is created once during application startup and reused for the lifetime of the application.◆ How Spring Boot Creates It (Automatically)
Spring Boot reads application.properties, builds the configuration, and calls internal Spring code to create an EntityManagerFactory bean — all automatically. You can observe this by placing a debug breakpoint inside LocalContainerEntityManagerFactoryBean.
◆ How to Create It Manually (For Multiple DBs)
1@Configuration2public class H2DatabaseConfig {3
4 // Step 1: Define the DataSource (equivalent to JDBC connection info)5 @Bean(name = "h2DataSource")6 public DataSource h2DataSource() {7 DriverManagerDataSource ds = new DriverManagerDataSource();8 ds.setDriverClassName("org.h2.Driver");9 ds.setUrl("jdbc:h2:mem:userdb");10 ds.setUsername("sa");11 ds.setPassword("");12 return ds;13 }14
15 // Step 2: Define the JPA Vendor Adapter (tells Spring which JPA provider to use)16 @Bean(name = "h2JpaVendorAdapter")17 public JpaVendorAdapter h2JpaVendorAdapter() {18 HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();19 adapter.setDatabase(Database.H2);20 adapter.setShowSql(true);21 adapter.setGenerateDdl(true);22 return adapter;23 }24
25 // Step 3: Create the EntityManagerFactory26 @Bean(name = "h2EntityManagerFactory")27 public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(28 @Qualifier("h2DataSource") DataSource dataSource,29 @Qualifier("h2JpaVendorAdapter") JpaVendorAdapter vendorAdapter) {30
31 LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();32 factory.setDataSource(dataSource);33 factory.setJpaVendorAdapter(vendorAdapter);34 factory.setPackagesToScan("com.example.entity.h2"); // Scan only these entities for H235 factory.setPersistenceUnitName("h2-unit");36 return factory;37 }38}A second configuration class (MySQLDatabaseConfig) would define its own DataSource, JpaVendorAdapter, and EntityManagerFactory in the same way.
4.3 Transaction Manager
◆ What Is It?
A Transaction Manager is a Spring bean responsible for:
- Beginning a transaction
- Committing a transaction
- Rolling back a transaction on failure
◆ Relationship With EntityManagerFactory
1One EntityManagerFactory → One TransactionManager2H2 EntityManagerFactory → H2 TransactionManager (RESOURCE_LOCAL)3MySQL EntityManagerFactory → MySQL TransactionManager (RESOURCE_LOCAL)◆ Types
| Type | Class | Scope |
|---|---|---|
RESOURCE_LOCAL | JpaTransactionManager | One DB only |
JTA | JtaTransactionManager | Multiple DBs (two-phase commit) |
JpaTransactionManager (RESOURCE_LOCAL) is what you use.◆ Creating a Transaction Manager Manually
1@Bean(name = "h2TransactionManager")2public PlatformTransactionManager h2TransactionManager(3 @Qualifier("h2EntityManagerFactory") EntityManagerFactory emf) {4 return new JpaTransactionManager(emf);5 // The EMF already knows the DataSource and all connection details,6 // so the TransactionManager can use it to manage transactions for that specific DB.7}◆ Startup Sequence (What Happens When Application Starts)
4.4 Entity Manager
◆ What Is It?
EntityManager is the core JPA interface you (or JPA Repository) use to interact with the database at runtime.
- It is not created at startup — it is created per operation / per request.
- It provides the actual CRUD API methods.
- It manages the Persistence Context for the duration of its operation.
◆ Entity Manager API Key Methods
| Method | SQL Equivalent | Purpose |
|---|---|---|
persist(entity) | INSERT | Save a new entity to DB |
merge(entity) | UPDATE | Update an existing entity |
find(Class, id) | SELECT ... WHERE id = ? | Fetch a single entity by primary key |
remove(entity) | DELETE | Delete an entity |
createQuery(jpql) | Custom SELECT | Execute a JPQL query |
flush() | Force sync | Immediately sync in-memory state to DB |
detach(entity) | — | Remove entity from Persistence Context |
close() | — | Close the EntityManager |
◆ Who Implements EntityManager?
EntityManager is a JPA interface. The actual implementation is provided by the JPA vendor:
| Vendor | Implementation Class |
|---|---|
| Hibernate | SessionImpl (also known as Session) |
| OpenJPA | OpenJPAEntityManager |
| EclipseLink | EclipseLinkEntityManager |
EntityManager is called a Session. When Hibernate documentation says "open a Session," it means creating an EntityManager object. The two are effectively the same concept with different names.◆ EntityManagerFactory EntityManager Relationship
1EntityManagerFactory (1) → EntityManager (many)2
3The factory creates new EntityManager instances as needed.4Each HTTP request / service call typically gets its own EntityManager.◆ Directly Using EntityManager (Without JPA Repository)
1@Service2public class UserServiceDirect {3
4 @PersistenceContext // Spring injects and manages the EntityManager5 private EntityManager entityManager;6
7 // ❌ This will throw TransactionRequiredException8 public void saveUserWithoutTransaction(UserDetails user) {9 entityManager.persist(user); // Requires an active transaction!10 }11
12 // ✅ Correct: add @Transactional13 @Transactional14 public void saveUser(UserDetails user) {15 entityManager.persist(user);16 }17
18 @Transactional19 public UserDetails getUser(Long id) {20 return entityManager.find(UserDetails.class, id); // Read — still good practice to have @Transactional21 }22}EntityManager.persist(), merge(), or remove() directly, you must have an active transaction. Without it, a TransactionRequiredException is thrown. JPA Repository handles this automatically — it annotates all write operations with @Transactional internally.4.5 Persistence Context
◆ What Is It?
The Persistence Context is an in-memory container (cache) that is automatically created alongside every EntityManager instance. It:
- Stores all entity objects that the current
EntityManageris working with - Acts as the first-level cache (L1 cache) — queries hit this before hitting the database
- Manages the lifecycle of each entity
- Synchronizes changes with the database at flush time
◆ One-to-One Relationship
1EntityManager (1) → Persistence Context (1)2
3Every EntityManager has exactly one associated Persistence Context.◆ Why It Exists The First-Level Cache Explained
When you call entityManager.find(UserDetails.class, 1L):
- JPA first checks the Persistence Context — "Do I already have this entity in memory?"
- If yes → returns it directly (no database query)
- If no → queries the database, stores the result in the Persistence Context, returns it
This is why in the demo, saving a user and then immediately fetching it showed only an INSERT in the console, not a SELECT — the fetch returned the entity from the Persistence Context (L1 cache) without hitting the database.
◆ What the Persistence Context Holds
1Persistence Context2├── UserDetails{id=1, name="Alice", email="alice@example.com"} ← fetched from DB3├── OrderDetails{id=42, status="PENDING"} ← being created4└── InvoiceDetails{id=7, amount=299.99} ← being updatedAll of these entities are "managed" — the Persistence Context tracks every change you make to them and ensures those changes are eventually flushed to the database.
4.6 Dialect
◆ What Is It?
Dialect is a Hibernate/JPA class that translates JPQL (Java Persistence Query Language) or HQL (Hibernate Query Language) into the native SQL dialect of the specific database being used.
Different databases have slightly different SQL syntax. The Dialect handles these differences transparently.
1Your JPQL Query: "SELECT u FROM UserDetails u WHERE u.name = :name"2 │3 Dialect translates4 │5H2 SQL: "SELECT user_details.id, user_details.name, user_details.email6 FROM user_details WHERE user_details.name = ?"7
8MySQL SQL: Same query, but with MySQL-specific optimizations and syntax◆ Common Dialect Classes
| Database | Hibernate Dialect Class |
|---|---|
| H2 | org.hibernate.dialect.H2Dialect |
| MySQL 8 | org.hibernate.dialect.MySQL8Dialect |
| PostgreSQL | org.hibernate.dialect.PostgreSQLDialect |
| Oracle | org.hibernate.dialect.OracleDialect |
| SQL Server | org.hibernate.dialect.SQLServerDialect |
◆ In Spring Boot (Auto-Detection)
Spring Boot automatically detects and sets the correct Dialect based on the DataSource driver on the classpath. You typically do not need to specify it in application.properties.
However, if you use a @Configuration class for manual setup, you must specify it explicitly:
1adapter.setDatabasePlatform("org.hibernate.dialect.MySQL8Dialect");◆ Dialect in the Architecture Flow
1EntityManager (Hibernate)2 │ speaks JPQL/HQL3 ▼4 Dialect5 │ translates to native SQL6 ▼7 JDBC8 │ sends SQL9 ▼10 Database5. Entity Lifecycle Inside Persistence Context
Every entity object goes through defined states within a Persistence Context. Understanding these states is critical for debugging and writing correct JPA code.
The Four States
State Descriptions
◆ 1. Transient (New)
- The entity object exists only in Java memory (heap).
- It has no connection to the Persistence Context.
- It has no corresponding row in the database.
1UserDetails user = new UserDetails(); // Transient state2user.setName("Alice");3user.setEmail("alice@example.com");4// At this point: exists in Java heap, not in DB, not in Persistence Context◆ 2. Managed
- The entity is inside the Persistence Context.
- The Persistence Context tracks every change made to this object.
- At flush time, all changes are automatically persisted to the database.
Two ways an entity becomes Managed:
Way 1 — New entity persisted:
1entityManager.persist(user);2// user is now Managed. Persistence Context tracks it.3// An INSERT will be issued when flush occurs.Way 2 — Fetched from DB:
1UserDetails user = entityManager.find(UserDetails.class, 1L);2// user is now Managed. It came from the DB and is in Persistence Context.3user.setName("Bob");4// No need to call merge/update — the change is automatically tracked!5// An UPDATE will be issued when flush occurs. (Dirty checking)◆ 3. Removed
- The entity is marked for deletion but may not yet be deleted from the database.
- Still exists in the Persistence Context in the Removed state.
- The actual
DELETESQL is issued when flush occurs.
1entityManager.remove(user);2// user is now in Removed state.3// DB still has the row (not yet flushed).4
5// Change your mind? You can bring it back:6entityManager.persist(user);7// user is back to Managed state. No DELETE will happen.◆ 4. Detached
- The entity was previously Managed (inside a Persistence Context), but the Persistence Context has been closed or the entity was explicitly detached.
- The entity object still exists in Java memory, but JPA is no longer tracking it.
- Any changes made to a Detached entity are not automatically synced to the database.
1entityManager.detach(user); // Explicitly detach one entity2// OR3entityManager.close(); // Closing the EntityManager detaches ALL its entities4
5// At this point, user is Detached. Changes won't be auto-synced.6user.setName("Charlie"); // This change is NOT tracked by JPA!7
8// To bring it back under JPA control:9UserDetails reattached = entityManager.merge(user);10// reattached is now Managed. The changes will be synced.Full Lifecycle Table
| State | In Persistence Context? | In Database? | Changes Tracked? |
|---|---|---|---|
| Transient | ❌ | ❌ | ❌ |
| Managed | ✅ | ✅ (or will be at flush) | ✅ (auto dirty-check) |
| Removed | ✅ (marked) | ✅ (until flush) | ❌ |
| Detached | ❌ | ✅ | ❌ |
6. JPA Repository vs Entity Manager Why Use JPA Repository?
Both JpaRepository and EntityManager can interact with the database, but JPA Repository adds significant convenience on top.
Comparison Table
| Feature | JpaRepository | EntityManager (Direct) |
|---|---|---|
Pre-built CRUD methods (save, findAll, findById, deleteById) | ✅ | ❌ (must write manually) |
| Pagination and Sorting support | ✅ (findAll(Pageable)) | ❌ (must implement manually) |
Automatic @Transactional on write ops | ✅ | ❌ (must add manually) |
| Automatic EntityManager lifecycle management | ✅ | ❌ (must manage) |
| Custom JPQL queries | ✅ (@Query annotation) | ✅ (createQuery) |
Batch operations (findAll, deleteAll) | ✅ | ❌ (must implement) |
JPA Repository Internally Uses EntityManager
1// Simplified internal implementation of SimpleJpaRepository.save()2@Transactional // ← Automatically applied3public <S extends T> S save(S entity) {4 if (entityInformation.isNew(entity)) {5 em.persist(entity); // ← Calls EntityManager.persist()6 return entity;7 } else {8 return em.merge(entity); // ← Calls EntityManager.merge()9 }10}7. First Level Caching (Introduction)
Note:
Full first-level caching is covered in Part 3. This section provides the foundational understanding from Part 2.
What Is It?
First-Level Cache (L1 Cache) is the Persistence Context itself. It is:
- Scoped to a single
EntityManager(and thus to a single transaction, by default) - Always enabled — you cannot disable it
- Transparent — it works automatically without any configuration
How It Works
1Request 1: findById(1) → Persistence Context miss → DB query → store in PC → return2Request 1: findById(1) → Persistence Context hit → return directly (NO DB query!)The Demo Observation Explained
In the lecture demo:
- A user was saved (
INSERTwas logged). - The same user was immediately fetched (
findById). - No
SELECTappeared in the console.
This happened because the save operation placed the entity in the Persistence Context. When findById was called immediately after (within the same transaction), JPA found the entity already in the Persistence Context and returned it directly — no database round-trip needed.
8. Multi-DB Setup Manual Configuration
When your Spring Boot application needs to connect to more than one database, you cannot use application.properties alone. You must create explicit @Configuration classes.
H2 Configuration Class
1@Configuration2@EnableJpaRepositories(3 basePackages = "com.example.repository.h2", // Repositories for H24 entityManagerFactoryRef = "h2EntityManagerFactory",5 transactionManagerRef = "h2TransactionManager"6)7public class H2Config {8
9 @Bean10 @ConfigurationProperties("spring.datasource.h2")11 public DataSource h2DataSource() {12 return DataSourceBuilder.create().build();13 }14
15 @Bean16 public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(17 @Qualifier("h2DataSource") DataSource dataSource) {18
19 HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();20 adapter.setDatabase(Database.H2);21 adapter.setShowSql(true);22 adapter.setGenerateDdl(true);23
24 LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();25 factory.setDataSource(dataSource);26 factory.setJpaVendorAdapter(adapter);27 factory.setPackagesToScan("com.example.entity.h2");28 factory.setPersistenceUnitName("h2-unit");29 return factory;30 }31
32 @Bean33 public PlatformTransactionManager h2TransactionManager(34 @Qualifier("h2EntityManagerFactory") EntityManagerFactory emf) {35 return new JpaTransactionManager(emf);36 }37}MySQL Configuration Class
1@Configuration2@EnableJpaRepositories(3 basePackages = "com.example.repository.mysql", // Repositories for MySQL4 entityManagerFactoryRef = "mysqlEntityManagerFactory",5 transactionManagerRef = "mysqlTransactionManager"6)7public class MySQLConfig {8
9 @Bean10 @ConfigurationProperties("spring.datasource.mysql")11 public DataSource mysqlDataSource() {12 return DataSourceBuilder.create().build();13 }14
15 @Bean16 public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(17 @Qualifier("mysqlDataSource") DataSource dataSource) {18
19 HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();20 adapter.setDatabase(Database.MYSQL);21 adapter.setGenerateDdl(false); // Don't auto-create tables in MySQL22
23 LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();24 factory.setDataSource(dataSource);25 factory.setJpaVendorAdapter(adapter);26 factory.setPackagesToScan("com.example.entity.mysql");27 factory.setPersistenceUnitName("mysql-unit");28 return factory;29 }30
31 @Bean32 public PlatformTransactionManager mysqlTransactionManager(33 @Qualifier("mysqlEntityManagerFactory") EntityManagerFactory emf) {34 return new JpaTransactionManager(emf);35 }36}`application.properties` for Multi-DB
1# H2 DataSource2spring.datasource.h2.url=jdbc:h2:mem:userdb3spring.datasource.h2.driver-class-name=org.h2.Driver4spring.datasource.h2.username=sa5spring.datasource.h2.password=6
7# MySQL DataSource8spring.datasource.mysql.url=jdbc:mysql://localhost:3306/ordersdb9spring.datasource.mysql.driver-class-name=com.mysql.cj.jdbc.Driver10spring.datasource.mysql.username=root11spring.datasource.mysql.password=secret@Configuration class for JPA, Spring Boot's auto-configuration backs off. You must explicitly configure everything: DataSource, JpaVendorAdapter, EntityManagerFactory, and TransactionManager.9. Common Mistakes & Best Practices
Common Mistakes
◆ Forgetting No-Arg Constructor on Entity
1// WRONG — JPA will fail to instantiate when loading from DB2@Entity3public class UserDetails {4 @Id5 private Long id;6 private String name;7 8 public UserDetails(Long id, String name) { // Only parameterized constructor9 this.id = id;10 this.name = name;11 }12}13
14// CORRECT — Always include no-arg constructor15@Entity16public class UserDetails {17 @Id18 private Long id;19 private String name;20 21 public UserDetails() {} // ← MANDATORY22 23 public UserDetails(Long id, String name) {24 this.id = id;25 this.name = name;26 }27}◆ Calling `EntityManager.persist()` Without a Transaction
1// WRONG — throws TransactionRequiredException2@Service3public class UserService {4 @PersistenceContext5 private EntityManager em;6 7 public void save(UserDetails user) {8 em.persist(user); // ❌ No transaction = exception9 }10}11
12// CORRECT13@Transactional // ← Must add this14public void save(UserDetails user) {15 em.persist(user);16}◆ Modifying a Detached Entity and Expecting Auto-Sync
1UserDetails user = entityManager.find(UserDetails.class, 1L);2entityManager.detach(user); // Detached!3user.setName("NewName"); // Change NOT tracked4// flush → No UPDATE will happen because entity is Detached◆ Using `application.properties` for Multi-DB Setup
Spring Boot's application.properties only supports a single DataSource. Attempting to add a second spring.datasource.* block will not work without @Configuration classes.
Best Practices
- Always use
JpaRepositoryunless you have a specific, justified reason to useEntityManagerdirectly. - Keep entities as simple POJOs — avoid business logic inside entities.
- One repository per entity — maintain clear separation.
- Never expose entities directly via REST APIs — use DTOs (Data Transfer Objects) to avoid serialization issues and over-exposure of data.
- Use
@Transactionalat the service layer, not the repository or controller layer. - Disable SQL logging in production (
spring.jpa.show-sql=false). - Use
@Table(name = "...")explicitly to avoid relying on naming convention defaults, especially when working with legacy databases.
10. Interview Notes
Commonly Asked Questions
Q: What is the difference between JPA and Hibernate?
JPA is a specification (interface/API standard) defined by Jakarta EE. Hibernate is an implementation of JPA. You code against JPA interfaces and Hibernate provides the actual logic underneath.
Q: What is a Persistence Context?
The Persistence Context is an in-memory storage area managed by an EntityManager. It holds all entities the EntityManager is currently working on, acts as the first-level cache, and manages entity lifecycle (Transient → Managed → Removed → Detached).
Q: What is the difference between persist() and merge()?
persist()is for new (Transient) entities — it inserts them.merge()is for Detached entities — it re-attaches them to the Persistence Context and issues an UPDATE if needed.
Q: What is first-level caching in Hibernate?
First-level caching is the Persistence Context itself. Within a single transaction/EntityManager, the same entity fetched multiple times returns from cache, not the database.
Q: What is a Dialect in Hibernate?
A Dialect is a class that translates JPQL/HQL into database-specific SQL. Different databases (MySQL, PostgreSQL, H2, Oracle) require different SQL syntax; the Dialect handles this translation transparently.
Q: What happens when you close an EntityManager?
All entities managed by that EntityManager transition to the Detached state. The Persistence Context is destroyed. Any unflushed changes are lost.
Q: What is EntityManagerFactory and why is it a singleton?
EntityManagerFactoryis the factory that createsEntityManagerinstances. It is heavyweight to create (reads all configuration, initializes Hibernate, maps entities) so it is created once at startup and reused. Creating one per request would be extremely slow.
Q: What is RESOURCE_LOCAL vs JTA transaction type?
RESOURCE_LOCALscopes a transaction to a single database.JTA(Java Transaction API) enables distributed transactions spanning multiple databases, using two-phase commit internally.
Q: What is the difference between persist() requiring @Transactional but find() not?
Write operations (INSERT, UPDATE, DELETE) modify the database and must be atomic — they require a transaction. Read operations (SELECT) do not modify data, so while they benefit from a transaction (for consistency), they do not strictly require one.
Q: Why does JpaRepository not require you to add @Transactional on write operations?
JpaRepository's underlying implementation class (SimpleJpaRepository) already annotates all write methods with@Transactionalinternally. This is one of the key benefits of using JPA Repository over direct EntityManager access.
11. Practice Questions
Easy
- What are the four steps required to set up a basic JPA application in Spring Boot?
- What annotation marks a Java class as a JPA entity?
- What is the purpose of the
@Idannotation? - What annotation is used for auto-incrementing primary keys?
- List three methods pre-built into
JpaRepository. - What does ORM stand for and what problem does it solve?
Medium
- Explain the relationship between
EntityManagerFactoryandEntityManager. - Draw the JPA architecture from
application.propertiesall the way to the database. - What are the four entity lifecycle states? Describe transitions between them.
- Why is a no-arg constructor mandatory for JPA entities?
- When would you use
entityManager.merge()instead ofentityManager.persist()? - What is the Persistence Context and how does it relate to first-level caching?
- Explain
RESOURCE_LOCALvsJTAtransaction types with a use case for each.
Hard
- How would you configure a Spring Boot application to connect to two separate databases (H2 and MySQL) simultaneously? Write the full configuration.
- Explain what happens internally when you call
userRepository.save(user)— trace the call from the repository through EntityManagerFactory, EntityManager, Persistence Context, Dialect, and JDBC. - Why does fetching an entity immediately after saving it (within the same transaction) not produce a
SELECTquery in the logs? What mechanism prevents this? - What would happen if you called
entityManager.detach(user), thenuser.setName("NewName"), thenentityManager.flush()? Would the name be updated in the database? - If you have a
@Transactionalservice method that callsfindById(), modifies the returned entity, and then the method returns — will the change be persisted? Explain the mechanism.
12. Summary
1JPA Architecture — At a Glance2────────────────────────────────────────────────────────────────────────3
4STARTUP (happens once):5 application.properties → Persistence Unit (config)6 Persistence Unit → EntityManagerFactory (1 per DB)7 EntityManagerFactory → TransactionManager (1 per EMF)8
9RUNTIME (happens per request):10 EntityManagerFactory → EntityManager (created on demand)11 EntityManager → Persistence Context (created alongside EM)12 EntityManager → Dialect → JDBC → Database13
14KEY CONCEPTS:15 • ORM = bridge between Java objects and DB tables16 • JPA = specification (interface); Hibernate = implementation17 • Persistence Unit = config grouping (≈ one DB)18 • EntityManagerFactory = singleton factory, expensive, created at startup19 • TransactionManager = manages begin/commit/rollback per DB20 • EntityManager = session with DB; all CRUD goes through this21 • Persistence Context = in-memory entity holder; L1 cache; lifecycle mgr22 • Dialect = JPQL → native SQL translator23
24ENTITY LIFECYCLE:25 Transient → (persist) → Managed → (remove) → Removed26 Managed → (detach / close) → Detached27 Detached → (merge) → Managed28
29JPA REPOSITORY vs ENTITY MANAGER:30 JPA Repository: high-level, pre-built CRUD, auto-@Transactional, pagination31 EntityManager: low-level, full control, manual transaction management requiredNext Up:
JPA Part 3 — First Level Caching (deep dive), Second Level Caching, and JPQL Queries.
Mastery check
How well can you recall this?
Finished this lesson?