JPA and Hibernate fundamentals
43 questions in 12 subtopics.
Entities and mapping
How do you map a custom value type, such as a Money class or a list of tags stored as a comma-separated string, to a single column in JPA?What is wrong with this entity?@Entity
public final class Product {
@Id
private Long id;
private String name;
private Status status;
public Product(String name) {
this.name = name;
}
}
Entity lifecycle states
Describe the four JPA entity states and whichEntityManager operations move an entity between them.This code throws 'detached entity passed to persist':Order o = orderRepository.findById(1L).get();
/* transaction ends */
o.setNote("x");
entityManager.persist(o);
entityManager.merge(detached) actually does, and why changes made to the detached object after calling merge are not saved.Persistence context
What is the persistence context (first-level cache), and what guarantee does it provide within a transaction?In Spring, theEntityManager injected with @PersistenceContext is a shared proxy used by many threads. How can that be thread-safe when EntityManager itself is not?A batch job that updates 2 million entities in one transaction slows down progressively and then fails with OutOfMemoryError. What is happening and how do you fix it?Some services use long-lived persistence contexts (extended contexts or a session kept for a whole user conversation), others use one per transaction. What standard would you set and why?EntityManager operations
What is the difference betweenentityManager.find(Order.class, id) and entityManager.getReference(Order.class, id)? When would you use getReference?What SQL does this code run, assuming the Customer exists and is not yet loaded? @Transactionalvoid rename(Long id, String n) {
Customer c = em.find(Customer.class, id);
c.setName(n);
em.persist(c);
em.flush();
em.refresh(c);
}
save() called after every setter, merge used for new entities with assigned ids, clear() called in random places. How would you raise the level of JPA usage across teams?Java persistence has moved through JDBC, EJB entity beans, Hibernate, JPA, javax to jakarta, and now Jakarta Data. Your codebase depends on JPA in 200 services. How would you plan for the next shift so it does not become a multi-year forced migration?Dirty checking and flush
What is dirty checking in Hibernate, and when does a flush happen by default?A developer is surprised that an UPDATE is sent to the database even though they never called save:@Transactional
public OrderDto view(Long id) {
Order o = repo.findById(id).orElseThrow();
o.setTotal(o.getTotal().setScale(2));
return map(o);
}
@DynamicUpdate and Hibernate bytecode enhancement change dirty checking and the SQL that is generated? When would you use them?Profiling shows a service spends 30 percent of CPU in Hibernate flush and dirty checking for requests that mostly read. What would you change?Identifier generation
CompareGenerationType.IDENTITY, SEQUENCE and UUID for primary keys in JPA with Hibernate.After a migration that created sequences with INCREMENT BY 1, a service using @SequenceGenerator with allocationSize = 50 starts throwing duplicate key errors. Explain.Choose an identifier strategy for a multi-region platform where records are created in several regions, merged into analytics, and exposed in public URLs.You must choose between staying on a commercial database with proprietary sequences, features and licence fees, or moving 60 JPA services to an open-source database. How do you assess the exit cost and decide?Years after choosing auto-increment integer ids, your company must merge databases from an acquisition and shard its own data. What does this teach about long-lived identifier decisions?Bootstrapping and configuring Hibernate
In a Spring Boot 3 or 4 application, how is Hibernate bootstrapped as the JPA provider, and where do you set Hibernate-specific properties such ashibernate.jdbc.batch_size?A service takes 40 seconds to start, and profiling shows most of it inside Hibernate's metadata building and schema validation for 900 entities. What would you look at?Several applications need two databases each (one PostgreSQL for orders, one for reporting). Define how you configure multiple persistence units in Spring Boot and how you keep this standard across teams.Entity callbacks, listeners and interceptors
FillcreatedAt and updatedAt on every entity automatically. Show a solution with JPA callbacks and one with Spring Data auditing.Compare JPA entity listeners, Hibernate Interceptor and Hibernate event listeners (for example PostUpdateEventListener). When would you use each?A @PostPersist listener sends a Kafka message that a new customer was created. Sometimes the message is sent but the customer is missing in the database. Why?Teams have scattered business logic in @PrePersist and @PreUpdate callbacks, leading to surprising behaviour and hard-to-test code. What guideline would you set?Natural ids
What is a Hibernate@NaturalId, and how does it differ from the primary key? Show how to load an entity by natural id.Should equals and hashCode of a JPA entity use the generated id or a natural id? Discuss with a Set<Book> mapped as a collection.Customer numbers were used as natural ids in many services, and now the business wants to renumber customers after a merger. How do you handle it?Immutable entities
What does@Immutable do on a Hibernate entity, and when would you use it?Design a ledger of account postings that must never be updated or deleted, mapped with JPA. How do you enforce immutability at every layer?Some architects propose making event or append-only records the main data model across your company, rather than mutable entities. What would you weigh before adopting it widely?Soft delete
Implement soft delete for a Customer entity so thatrepository.delete(customer) sets deleted = true and normal queries do not return deleted rows. Show the Hibernate 6.4 or later way and the older way.After introducing soft delete, a customer cannot register again with the same email, reports count deleted customers, and the table keeps growing. How do you address these issues?Different teams implement soft delete in different ways (flags, status values, deleted_at columns, archive tables). Should you standardise it, and how?Common Hibernate errors
Explain the cause and the fix for each: (a)LazyInitializationException: could not initialize proxy - no Session, (b) MultipleBagFetchException: cannot simultaneously fetch multiple bags, (c) TransientPropertyValueException: object references an unsaved transient instance.Logs show 'org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction' (wrapped as ObjectOptimisticLockingFailureException in Spring) under load. What does it tell you and how do you respond?Hibernate errors such as LazyInitializationException, N+1 queries and optimistic lock failures keep appearing in incident reviews across teams. What would you do as the senior engineer for the data layer?No question matches these choices.