1. JPA / Jakarta Persistence
Jakarta Persistence is the standard API/specification for persistence and ORM in Java. Hibernate is a popular provider implementing the specification.
Modern namespace: Use jakarta.persistence.* for current Jakarta Persistence applications. The old javax.persistence.* namespace belongs to older generations of the specification.
| Concept | Role |
|---|
| Entity | Persistent domain object. |
| EntityManagerFactory | Creates EntityManagers for a persistence unit. |
| EntityManager | Interacts with the persistence context and performs persistence operations. |
| Persistence Context | Set of managed entity instances and their lifecycle tracking. |
2. Entity Program
import jakarta.persistence.*;
@Entity
@Table(name = "campaign")
public class Campaign {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private boolean active;
protected Campaign() {}
public Campaign(String name, boolean active) {
this.name = name;
this.active = active;
}
// getters and setters
}
Important Annotations
| Annotation | Purpose |
|---|
| @Entity | Marks a class as a persistent entity. |
| @Id | Identifies the primary key. |
| @GeneratedValue | Configures identifier generation. |
| @Table | Maps entity to a table name/options. |
| @Column | Maps/configures a persistent field/property. |
| @Version | Supports optimistic locking. |
3. EntityManager CRUD
EntityManager em = entityManagerFactory.createEntityManager();
try {
EntityTransaction tx = em.getTransaction();
tx.begin();
Campaign c = new Campaign("Spring Project", true);
em.persist(c); // CREATE
Campaign loaded =
em.find(Campaign.class, c.getId()); // READ
loaded.setActive(false); // UPDATE
em.remove(loaded); // DELETE
tx.commit();
} finally {
em.close();
}
find() returns the managed entity when found, otherwise null. getReference() can return a reference whose database access may be deferred until needed.
4. Spring Data JPA Repository
Current Repository Concept
public interface CampaignRepository
extends JpaRepository<Campaign, Long> {
List<Campaign> findByActiveTrue();
Optional<Campaign> findByName(String name);
}
| Interface | Main purpose |
|---|
| Repository | Marker/base abstraction. |
| CrudRepository | CRUD methods. |
| PagingAndSortingRepository | Paging and sorting operations. |
| JpaRepository | JPA-specific repository extension with richer CRUD/paging functionality. |
Current API note: Recent Spring Data versions also expose ListCrudRepository and ListPagingAndSortingRepository. Therefore older diagrams that show only JpaRepository → PagingAndSortingRepository → CrudRepository are useful conceptually but are not the complete current inheritance definition.
6. JPQL and Criteria API
JPQL
TypedQuery<Campaign> query =
entityManager.createQuery(
"select c from Campaign c " +
"where c.active = :active " +
"and c.name like :name",
Campaign.class);
query.setParameter("active", true);
query.setParameter("name", "%Spring%");
List<Campaign> campaigns = query.getResultList();
Criteria API
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Campaign> cq = cb.createQuery(Campaign.class);
Root<Campaign> root = cq.from(Campaign.class);
cq.select(root)
.where(
cb.and(
cb.isTrue(root.get("active")),
cb.like(root.get("name"), "%Spring%")
)
);
List<Campaign> result =
entityManager.createQuery(cq).getResultList();
Do not confuse: Jakarta Persistence Criteria API is the standard API. Hibernate's old proprietary Criteria API is legacy and should not be presented as the current JPA Criteria solution.
7. Relationship Mapping
@Entity
class Department {
@Id @GeneratedValue
private Long id;
@OneToMany(mappedBy = "department",
cascade = CascadeType.ALL,
orphanRemoval = true)
private List<Employee> employees = new ArrayList<>();
}
@Entity
class Employee {
@Id @GeneratedValue
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Department department;
}
Common Mappings
| Mapping | Typical use |
|---|
| @OneToOne | One entity corresponds to one related entity. |
| @OneToMany | Parent with a collection of children. |
| @ManyToOne | Many rows/entities point to one parent. |
| @ManyToMany | Many entities relate to many others, usually through a join table. |
8. Transactions with Spring Data JPA
@Service
public class CampaignService {
private final CampaignRepository repository;
public CampaignService(CampaignRepository repository) {
this.repository = repository;
}
@Transactional
public void publish(Long id) {
Campaign c = repository.findById(id)
.orElseThrow();
c.setActive(true);
// Managed entity changes are synchronized with the DB
// when the persistence context is flushed/transaction completes.
}
@Transactional(readOnly = true)
public Campaign get(Long id) {
return repository.findById(id).orElseThrow();
}
}
Transaction boundaries are commonly placed around service-level business operations so multiple repository calls can participate in one logical unit of work.
9. Propagation and Isolation
| Propagation | Meaning |
|---|
| REQUIRED | Join existing or create new; default. |
| REQUIRES_NEW | Suspend existing and create new. |
| SUPPORTS | Join if one exists; otherwise none. |
| NOT_SUPPORTED | Suspend existing and run without one. |
| MANDATORY | Existing transaction required. |
| NEVER | Must not have an existing transaction. |
| NESTED | Nested/savepoint behavior when supported. |
| Isolation | General behavior |
|---|
| READ_UNCOMMITTED | Lowest isolation; dirty reads may occur. |
| READ_COMMITTED | Prevents dirty reads. |
| REPEATABLE_READ | Provides stronger repeat-read guarantees. |
| SERIALIZABLE | Highest standard isolation; stronger concurrency constraints. |
10. Rollback Rules
@Transactional(
rollbackFor = {
IOException.class,
CustomBusinessException.class
}
)
public void process() throws IOException, CustomBusinessException {
// work
}
By default, Spring's declarative transaction support rolls back for unchecked exceptions (RuntimeException) and Error. Checked exceptions require explicit rollback rules when rollback is desired.
Self Invocation
@Transactional
public void outer() {
inner(); // direct same-object call; proxy is bypassed
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void inner() {
// REQUIRES_NEW advice is not applied by this self-call.
}
11. Complete Spring Boot JPA Program
Entity
@Entity
public class Product {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private BigDecimal price;
protected Product() {}
public Product(String name, BigDecimal price) {
this.name = name;
this.price = price;
}
// getters/setters
}
Repository
public interface ProductRepository
extends JpaRepository<Product, Long> {
Page<Product> findByNameContainingIgnoreCase(
String name, Pageable pageable);
}
Service
@Service
public class ProductService {
private final ProductRepository repository;
public ProductService(ProductRepository repository) {
this.repository = repository;
}
@Transactional
public Product create(String name, BigDecimal price) {
return repository.save(new Product(name, price));
}
@Transactional(readOnly = true)
public Page<Product> search(
String name, int page, int size) {
return repository.findByNameContainingIgnoreCase(
name,
PageRequest.of(page, size, Sort.by("name"))
);
}
}
REST Controller
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService service;
public ProductController(ProductService service) {
this.service = service;
}
@GetMapping
public Page<Product> search(
@RequestParam(defaultValue = "") String name,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return service.search(name, page, size);
}
}
12. JPA Interview Revision
| Question | Answer |
| What is JPA? | Jakarta Persistence standard/API for persistence and ORM. |
| Hibernate vs JPA? | Hibernate is a provider; JPA/Jakarta Persistence is the standard. |
| EntityManagerFactory? | Factory for EntityManagers and persistence-unit infrastructure. |
| EntityManager? | API for persistence-context interaction and entity operations. |
| What is a persistence context? | A context tracking managed entity instances and their state. |
| What is pagination? | Retrieving results in bounded chunks rather than loading everything. |
| What is N+1? | One query for a parent set plus repeated additional queries for related data. |
| What is @Transactional? | Declarative transaction boundary/semantics managed by Spring. |
| Default propagation? | REQUIRED. |
| Default isolation? | DEFAULT, delegating to the underlying system/database. |
| Why service-layer transactions? | They align the transaction with a business operation and can span multiple repository calls. |