JPA / Jakarta Persistence – Latest Validated Notes

Jakarta Persistence 3.2 aligned • EntityManager • Entity Mapping • Spring Data JPA • Pagination • JPQL • Criteria • Relationships • Transactions

Contents

  1. JPA / Jakarta Persistence
  2. Entity Program
  3. EntityManager CRUD
  4. Spring Data JPA Repositories
  5. Pagination
  6. JPQL / Criteria
  7. Relationships
  8. Transactions
  9. Propagation & Isolation
  10. Rollback Rules
  11. Spring Boot JPA Program
  12. Interview Revision

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.
ConceptRole
EntityPersistent domain object.
EntityManagerFactoryCreates EntityManagers for a persistence unit.
EntityManagerInteracts with the persistence context and performs persistence operations.
Persistence ContextSet 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

AnnotationPurpose
@EntityMarks a class as a persistent entity.
@IdIdentifies the primary key.
@GeneratedValueConfigures identifier generation.
@TableMaps entity to a table name/options.
@ColumnMaps/configures a persistent field/property.
@VersionSupports 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);
}
InterfaceMain purpose
RepositoryMarker/base abstraction.
CrudRepositoryCRUD methods.
PagingAndSortingRepositoryPaging and sorting operations.
JpaRepositoryJPA-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.

5. Pagination

Spring Data JPA – Recommended Repository Style

public interface CampaignRepository
        extends JpaRepository<Campaign, Long> {

    Page<Campaign> findByActiveTrue(Pageable pageable);
}

@Service
public class CampaignService {

    private final CampaignRepository repository;

    public CampaignService(CampaignRepository repository) {
        this.repository = repository;
    }

    @Transactional(readOnly = true)
    public Page<Campaign> find(int page, int size) {
        Pageable pageable =
            PageRequest.of(page, size,
                Sort.by("name").ascending());

        return repository.findByActiveTrue(pageable);
    }
}

Important: Spring Data page indexes are zero-based. PageRequest.of(0, 20) is the first page.

EntityManager Pagination

TypedQuery<Campaign> query =
    entityManager.createQuery(
        "select c from Campaign c order by c.name",
        Campaign.class);

int pageNumber = 1; // API-level 1-based page
int pageSize = 20;

query.setFirstResult((pageNumber - 1) * pageSize);
query.setMaxResults(pageSize);

List<Campaign> result = query.getResultList();

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

MappingTypical use
@OneToOneOne entity corresponds to one related entity.
@OneToManyParent with a collection of children.
@ManyToOneMany rows/entities point to one parent.
@ManyToManyMany 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

PropagationMeaning
REQUIREDJoin existing or create new; default.
REQUIRES_NEWSuspend existing and create new.
SUPPORTSJoin if one exists; otherwise none.
NOT_SUPPORTEDSuspend existing and run without one.
MANDATORYExisting transaction required.
NEVERMust not have an existing transaction.
NESTEDNested/savepoint behavior when supported.
IsolationGeneral behavior
READ_UNCOMMITTEDLowest isolation; dirty reads may occur.
READ_COMMITTEDPrevents dirty reads.
REPEATABLE_READProvides stronger repeat-read guarantees.
SERIALIZABLEHighest 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

QuestionAnswer
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.