Data Access with JPA and Hibernate

Entity design, fetching strategies, the N+1 problem, transactions and isolation, optimistic locking, batching, projections and when to use jOOQ or plain JDBC instead.

Entity design guidelines

  • Use LAZY fetching for associations by default (@ManyToOne(fetch = LAZY); the JPA default for to-one is eager).
  • Keep aggregates small; avoid bidirectional associations unless needed.
  • Use @Version for optimistic locking on concurrently updated entities.
  • Prefer database-generated sequences with pooled optimizers over IDENTITY when batch inserts matter.
  • Map value objects with @Embeddable.
@Entity
@Table(name = "orders")
class OrderEntity {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
    @SequenceGenerator(name = "order_seq", sequenceName = "order_seq", allocationSize = 50)
    Long id;

    @ManyToOne(fetch = FetchType.LAZY) Customer customer;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    List<OrderLineEntity> lines = new ArrayList<>();

    @Version long version;
}

The N+1 problem

Loading 100 orders and then accessing order.getLines() triggers 1 + 100 queries.

// Fix 1: fetch join for a specific use case
@Query("select distinct o from OrderEntity o join fetch o.lines where o.customer.id = :cid")
List<OrderEntity> withLines(@Param("cid") Long customerId);

// Fix 2: entity graph
@EntityGraph(attributePaths = "lines")
List<OrderEntity> findByCustomerId(Long customerId);

// Fix 3: batch fetching (hibernate.default_batch_fetch_size=50)

// Fix 4: DTO projection for read-only views
@Query("select new com.acme.OrderSummary(o.id, o.status, o.total) from OrderEntity o where o.customer.id = :cid")
List<OrderSummary> summaries(@Param("cid") Long customerId);

Detect N+1 with SQL logging in tests, Hibernate statistics, or assertion libraries that count queries.

Transactions

  • @Transactional on application services, not repositories or controllers.
  • Keep transactions short; never call remote services inside a DB transaction.
  • readOnly = true for queries (allows optimizations).
  • Know isolation defaults; use SELECT ... FOR UPDATE (pessimistic) or @Version (optimistic) for contested updates.

Batching

spring.jpa.properties.hibernate:
  jdbc.batch_size: 50
  order_inserts: true
  order_updates: true

When not to use JPA

Reporting queries, complex SQL, bulk updates and performance-critical paths often fit jOOQ (type-safe SQL), Spring JdbcClient, or plain SQL better. Mixing is fine: JPA for aggregates, SQL for reads.

Interview questions and answers

What is the difference between optimistic and pessimistic locking?

Optimistic locking detects conflicts at commit using a version column and fails one transaction (retry it); best for low contention. Pessimistic locking acquires row locks up front (FOR UPDATE), preventing conflicts but reducing concurrency and risking deadlocks; best for high contention on few rows.

Why is open-session-in-view harmful?

It keeps the persistence context open during view rendering, triggering lazy-loading queries outside the service layer, causing hidden N+1 queries and long-held database connections.