Scrivio Interview library

JPA and Hibernate fundamentals

43 questions in 12 subtopics.

Entities and mapping

ConceptFoundations6 min read
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?
CodingFoundations6 min read
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;
}
}
DesignIntermediate7 min read
You are mapping a legacy schema with composite primary keys, columns named in a different convention and some tables with no primary key. How do you approach the JPA mapping?
LeadershipPrincipal7 min read
Your company's entity model is shared as a library by 15 services that all read and write the same database. Over the years, every schema change needs all teams. What would you change, and over what timeframe?

Entity lifecycle states

ConceptFoundations5 min read
Describe the four JPA entity states and which EntityManager operations move an entity between them.
DebuggingFoundations6 min read
This code throws 'detached entity passed to persist':
Order o = orderRepository.findById(1L).get();
/* transaction ends */
o.setNote("x");
entityManager.persist(o);
Why, and what should it do?
InternalsIntermediate6 min read
Explain what entityManager.merge(detached) actually does, and why changes made to the detached object after calling merge are not saved.

Persistence context

ConceptFoundations6 min read
What is the persistence context (first-level cache), and what guarantee does it provide within a transaction?
InternalsIntermediate6 min read
In Spring, the EntityManager injected with @PersistenceContext is a shared proxy used by many threads. How can that be thread-safe when EntityManager itself is not?
DebuggingIntermediate7 min read
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?
DesignAdvanced7 min read
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

ConceptFoundations6 min read
What is the difference between entityManager.find(Order.class, id) and entityManager.getReference(Order.class, id)? When would you use getReference?
CodingIntermediate6 min read
What SQL does this code run, assuming the Customer exists and is not yet loaded? @Transactional
void rename(Long id, String n) {
Customer c = em.find(Customer.class, id);
c.setName(n);
em.persist(c);
em.flush();
em.refresh(c);
}
ScenarioAdvanced6 min read
Code reviews across teams show frequent misuse of JPA operations: 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?
LeadershipPrincipal6 min read
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

ConceptFoundations6 min read
What is dirty checking in Hibernate, and when does a flush happen by default?
DebuggingFoundations6 min read
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);
}
Explain.
InternalsIntermediate6 min read
How do @DynamicUpdate and Hibernate bytecode enhancement change dirty checking and the SQL that is generated? When would you use them?
ScenarioAdvanced6 min read
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

ConceptFoundations6 min read
Compare GenerationType.IDENTITY, SEQUENCE and UUID for primary keys in JPA with Hibernate.
DebuggingIntermediate6 min read
After a migration that created sequences with INCREMENT BY 1, a service using @SequenceGenerator with allocationSize = 50 starts throwing duplicate key errors. Explain.
DesignAdvanced6 min read
Choose an identifier strategy for a multi-region platform where records are created in several regions, merged into analytics, and exposed in public URLs.
ScenarioPrincipal7 min read
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?
LeadershipPrincipal6 min read
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

ConceptFoundations6 min read
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 as hibernate.jdbc.batch_size?
DebuggingIntermediate6 min read
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?
DesignAdvanced5 min read
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

CodingFoundations6 min read
Fill createdAt and updatedAt on every entity automatically. Show a solution with JPA callbacks and one with Spring Data auditing.
ConceptIntermediate6 min read
Compare JPA entity listeners, Hibernate Interceptor and Hibernate event listeners (for example PostUpdateEventListener). When would you use each?
DebuggingIntermediate6 min read
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?
DesignAdvanced6 min read
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

ConceptFoundations6 min read
What is a Hibernate @NaturalId, and how does it differ from the primary key? Show how to load an entity by natural id.
DesignIntermediate7 min read
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.
ScenarioAdvanced6 min read
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

ConceptFoundations6 min read
What does @Immutable do on a Hibernate entity, and when would you use it?
DesignIntermediate8 min read
Design a ledger of account postings that must never be updated or deleted, mapped with JPA. How do you enforce immutability at every layer?
LeadershipPrincipal6 min read
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

CodingFoundations6 min read
Implement soft delete for a Customer entity so that repository.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.
ScenarioIntermediate7 min read
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?
DesignAdvanced6 min read
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

DebuggingFoundations7 min read
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.
DebuggingIntermediate6 min read
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?
ScenarioAdvanced6 min read
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?