← All topics
Start ▶
Hibernate and JPA
Entity lifecycle, lazy loading, N+1 and caching.
200 questions
Level:
No questions match — try other words or turn a level back on.
1
What's the difference between JPA and Hibernate?
JPA (now Jakarta Persistence) is a specification: a set of annotations and interfaces. Hibernate is its most popular implementation, and it adds extra features of its own on top.
2
What is ORM and what problem does it solve?
ORM is a layer that automatically converts Java objects to table rows and back. It removes hand-written JDBC code, building objects from a ResultSet, and plain CRUD SQL.
3
What requirements must a class meet to be an @Entity?
The class needs @Entity, an @Id, and a public or protected no-arg constructor. It should not be final, and its persistent fields and methods should not be final either, otherwise Hibernate can't create a proxy.
4
How do the IDENTITY, SEQUENCE and UUID strategies in @GeneratedValue differ?
With IDENTITY the database's auto-increment column provides the id. With SEQUENCE Hibernate takes values from a separate sequence and can reserve them in advance. With UUID the application itself generates the id. On PostgreSQL, SEQUENCE is usually the best choice.
5
If you leave out @Table and @Column, how does Hibernate choose table and column names?
Those annotations let you set the table and column name, length, nullability and other properties explicitly. If you leave them out, Hibernate derives the names from the class and field names using the naming strategy.
6
Explain the entity lifecycle states: transient, managed, detached and removed.
Transient is an object created with new that Hibernate doesn't know about. Managed is an object the persistence context is tracking. Detached was managed before, but its context was closed or the object was detached from it. Removed is marked for deletion and gets a DELETE on flush.
7
What is the persistence context?
The persistence context is the set of managed entities inside one EntityManager (a Session in Hibernate). It keeps one object per id, tracks changes, and turns them into SQL on flush.
8
How are EntityManager and the Hibernate Session related?
EntityManager is the JPA interface and Session is Hibernate's. In Hibernate 6, Session extends EntityManager directly, so they are the same object. When you need Hibernate's API, you switch to it with em.unwrap(Session.class).
9
What's the difference between persist() and merge()?
persist() makes the new (transient) object itself managed and returns nothing. merge() copies the state of a detached or new object onto a managed copy and returns that copy. The object you passed in does not become managed.
10
What's the difference between find() and getReference()?
find() goes to the database immediately and returns null if nothing is found. getReference() returns a proxy without a SELECT. The database is read only when you touch a field of the proxy, and if the row doesn't exist, that's when EntityNotFoundException is thrown.
11
How does dirty checking work in Hibernate?
When an entity becomes managed, Hibernate keeps a copy (a snapshot) of its state as it was loaded. On flush it compares the current fields to the snapshot and, if they differ, sends the UPDATE itself. You don't need to call save().
12
What does flush() do and how is it different from commit?
flush() sends the changes accumulated in the persistence context to the database as SQL, but doesn't end the transaction. Commit confirms the transaction, and Hibernate flushes by itself before that. If you roll back after a flush, the changes are still undone.
13
What's the difference between lazy and eager loading?
With eager, the related object is loaded right away together with the main entity. With lazy, a proxy or an empty collection wrapper is put in its place, and the data is read only the first time you access it.
14
What is the default fetch type for each kind of association?
@ManyToOne and @OneToOne default to EAGER. @OneToMany and @ManyToMany default to LAZY. In other words, associations that point to a single object are eager and collections are lazy.
15
Why does LazyInitializationException get thrown?
It is thrown when you access a lazy proxy or collection after the persistence context (session) has been closed. Hibernate needs to read the data, but there is no open session anymore.
16
What is the N+1 problem?
You fetch N main records with one query, then read the related data for each of them with a separate query. The result is 1 + N SELECTs; for 1000 records that means 1001 queries.
17
How does JOIN FETCH in JPQL differ from a plain JOIN?
A plain JOIN only adds the table for filtering or a condition and does not load the related entities. JOIN FETCH reads the related objects in the same query and fills them into the entity.
18
How do you write a bidirectional association with @OneToMany and @ManyToOne, and why is mappedBy needed?
The foreign key lives in the child table, so the @ManyToOne side is the owning side. On the parent side you write @OneToMany(mappedBy = "..."), which tells Hibernate "this association is managed through that field; don't create a separate column or table."
19
What is the owning side of an association and why does it matter?
The owning side is the side that determines which field sets the foreign key value. When Hibernate writes to the database, it looks only at that side. Changes on the inverse (mappedBy) side don't affect the database.
20
What does the @JoinColumn annotation do?
@JoinColumn defines the name and properties of the foreign key column: its name, nullability, and which column it references. If you leave it out, Hibernate builds the name itself in the form field_id.
21
How is a @ManyToMany association stored in the database?
Through an intermediate (join) table that holds the ids of both sides as foreign keys. One side is the owner and names the table with @JoinTable; the other side writes mappedBy.
22
What CascadeType values are there and what does each one mean?
Cascade means passing an operation on the parent entity down to the related entities. The types are PERSIST, MERGE, REMOVE, REFRESH, DETACH, and ALL, which combines them all.
23
What does orphanRemoval = true do and how is it different from CascadeType.REMOVE?
orphanRemoval deletes a child from the database when it is removed from the parent's collection. CascadeType.REMOVE deletes the children only when the parent itself is deleted; taking one out of the collection has no effect on it.
24
What is JPQL and how does it differ from SQL?
JPQL is a query language written against entities and their fields; Hibernate translates it into the database's SQL dialect. SQL works with table and column names, while JPQL works with class names and Java field names.
25
How should you pass a value into a JPQL query, and why is concatenating a string dangerous?
Pass values as parameters: named (:name) or positional (?1). If you build the string with +, you open the door to SQL (JPQL) injection, and a new query plan gets built for every different value.
26
How does the @Transient annotation differ from Java's transient keyword?
@Transient makes only Hibernate ignore the field: it isn't written to the database, but it still takes part in Java serialization. The transient keyword excludes the field from Java serialization, and Hibernate doesn't persist it either.
27
When persisting an enum field, would you choose EnumType.ORDINAL or EnumType.STRING?
Almost always STRING. ORDINAL stores the enum's position number, and if a new value is added in the middle or the order changes, the old data in the database silently takes on the wrong meaning.
28
What is Hibernate's first-level cache?
It is the persistence context itself: entities loaded by id within one session are kept here. It is always on, can't be turned off, and disappears when the session closes.
29
What is the second-level cache and how does it differ from the first-level cache?
The second-level cache lives at the SessionFactory level and is shared by all sessions. It is off by default and needs a separate provider (for example Ehcache or Caffeine through JCache) and explicit opt-in per entity.
30
What are the values of spring.jpa.hibernate.ddl-auto, and which one should you use in prod?
The values are none, validate, update, create and create-drop. In prod you use none or validate, and Flyway or Liquibase migrations manage the schema.
31
How do you see the SQL queries and parameters Hibernate is sending?
The simplest way is to set the org.hibernate.SQL logger to DEBUG, and for parameter values set org.hibernate.orm.jdbc.bind to TRACE (Hibernate 6). show-sql=true works too, but it uses System.out, not a logger.
32
When are @Embeddable and @Embedded used?
They let you place a value object inside an entity without a separate table or its own id. The fields of the @Embeddable class become columns in the owner's table, for example Address or Money.
33
Why does an entity class have to have a no-arg constructor?
When Hibernate reads a row from the database, it doesn't know which constructor to call or with what arguments. It creates an empty object with the no-arg constructor and then fills in the fields through reflection. Proxy classes rely on that constructor too.
34
What actually happens inside the save() method in Spring Data JPA?
SimpleJpaRepository.save() checks whether the entity is new: if it is, it calls em.persist(), otherwise em.merge(), and returns the result. It usually decides that an entity is new from its id (or @Version) being null.
35
What is the field annotated with @Version for?
@Version turns on optimistic locking. On every UPDATE Hibernate checks and increments the version; if another transaction changed the row in the meantime, the UPDATE touches no rows and an OptimisticLockException is thrown.
36
What strategies does Hibernate offer for mapping inheritance to the database?
Three. SINGLE_TABLE puts the whole hierarchy in one table, with a discriminator column marking the type. JOINED gives each class its own table, assembled with joins. TABLE_PER_CLASS gives each concrete class a full table of its own.
37
What is @MappedSuperclass and how does it differ from inheritance with @Entity?
@MappedSuperclass is a parent class that collects common fields (id, createdAt, version) in one place. It has no table of its own and is not an entity. You can't query it or reference it; only its fields are copied into the subclasses' tables.
38
When do you write a native SQL query instead of JPQL?
When you need something specific to the database: PostgreSQL jsonb operators, ON CONFLICT, special index hints, complex window functions, or optimized SQL handed over by a DBA. For plain CRUD and filters, JPQL is enough.
39
After the method below is called, does the user's name change in the database?
Yes, it does. The entity was loaded inside the transaction, so it is managed, and dirty checking finds the change before commit and sends the UPDATE itself. save() isn't needed.
40
What are lifecycle callbacks like @PrePersist and @PreUpdate used for?
They are methods that get called automatically at certain points in an entity's lifecycle: before saving, before updating, after loading, and so on. They're mostly used to set createdAt/updatedAt, assign default values, or do simple checks.
41
How should you write equals() and hashCode() for an entity, and what's the problem with a generated id?
A generated id is null until persist and gets a value afterward. If hashCode is computed from the id, the hash changes after the object has been added to a HashSet, and you can no longer find it in the set. Usually you use a natural key, or write equals based on the id and a constant hashCode.
42
What problems come up if you put Lombok's @Data on entities?
@Data generates equals, hashCode and toString over all fields. With a bidirectional association this leads to StackOverflowError, and with lazy fields it leads to unexpected SELECTs or LazyInitializationException.
43
Why does MultipleBagFetchException get thrown when you JOIN FETCH two List collections in one query?
Hibernate treats an unordered, unindexed List as a "bag". If you join two bags in one SQL statement, the result turns into a Cartesian product, and Hibernate can't reliably tell which row belongs to which collection, so it forbids this outright.
44
I set hibernate.jdbc.batch_size, but the INSERTs still go one at a time. What could the cause be?
The most common cause is GenerationType.IDENTITY: to get the id, Hibernate runs every INSERT immediately and separately, which disables batching. Other causes are mixed entity types being saved interleaved (no order_inserts) or checking for batching the wrong way in the logs.
45
What is spring.jpa.open-in-view, and why does Spring Boot warn you about it at startup?
Open-in-view (OSIV) keeps the persistence context open for the whole HTTP request, until the view or JSON is written. In Spring Boot it's true by default. That's why touching lazy fields in a controller works without errors, but at the cost of hidden SQL and a DB connection held for a long time.
46
If you need only a field or two, how do you use a projection instead of the entity?
In JPQL you read directly into a DTO or record with select new, and in Spring Data into an interface or record projection. Only the columns you need are SELECTed, the objects don't land in the persistence context, and there is no dirty checking.
47
What is a pessimistic lock and how do you get one in JPA?
A pessimistic lock locks the database row at the moment of reading, so other transactions can't change it and wait for the commit. In JPA you get it with LockModeType.PESSIMISTIC_WRITE, which usually turns into SELECT ... FOR UPDATE.
48
What does @Transactional(readOnly = true) actually change at the Hibernate level?
Spring puts the Hibernate session into read-only mode and sets the flush mode to MANUAL. As a result, no snapshots are kept for loaded entities and there is no dirty checking or flush; the JDBC connection is also marked read-only.
49
Which price does the last line of this code print, and why?
The old price, 100. A bulk JPQL UPDATE goes straight to the database and does not update the Product object that is already loaded in the persistence context.
50
When does getSingleResult() throw an exception, and how do you write a query that may return no result?
If nothing is found it throws NoResultException, and if more than one row comes back it throws NonUniqueResultException. For a query that may be empty, use getResultStream().findFirst(), or in Spring Data a method that returns Optional.
51
`save()` is never called in this method, but the price still changes in the database. Why?
The entity returned by findById is managed. At the end of the transaction Hibernate runs dirty checking: it sees the changed field and sends the UPDATE itself. save() isn't needed here at all.
52
What happens in Hibernate if you make an entity class or its fields `final`?
Hibernate can't create a proxy subclass of a final class, so a lazy @ManyToOne in practice loads immediately. The JPA specification forbids final fields: Hibernate tries to fill them through reflection, but you can't rely on that.
53
Why can't Hibernate batch INSERTs when `GenerationType.IDENTITY` is used?
With IDENTITY, the database assigns the id during the INSERT. Hibernate needs to know the id right away to make the entity managed, so on every persist() it sends the INSERT immediately and separately, and JDBC batching is effectively off.
54
What time zone problems come up when persisting `LocalDateTime`, `Instant` and `OffsetDateTime` fields?
LocalDateTime has no zone: it's stored exactly as you write it, and its meaning shifts if the server's zone changes. Instant is an exact point in time, but the JVM zone can interfere when it's passed to JDBC. Setting hibernate.jdbc.time_zone=UTC and making the column timestamptz is the safest route.
55
What happens if you replace a collection with `orphanRemoval = true` wholesale using `setItems(newList)`?
Hibernate tracks the collection through its own PersistentBag/PersistentSet wrapper. If you replace it with a new ArrayList, the flush fails with "A collection with cascade=all-delete-orphan was no longer referenced". The right way is to clear() the existing collection and add the elements again.
56
In a bidirectional association, if you add an element only to the collection on the `mappedBy` side, what gets written to the database?
Nothing. The owning side controls the FK, which is the side with @ManyToOne. Hibernate ignores changes in the mappedBy collection for the FK, so you must also call child.setParent(parent).
57
How does `@Column(nullable = false)` differ from Bean Validation's `@NotNull`?
@Column(nullable = false) is mostly for DDL: if Hibernate creates the schema, it puts NOT NULL on the column, and the database does the checking. @NotNull is Java-level validation: Hibernate checks it before persist/update and throws an error before the SQL is even sent.
58
How is field access versus property access chosen for an entity, and why does it matter where you put `@Id`?
Hibernate determines the access type from where @Id is placed: on a field means field access, on a getter means property access. The other annotations must sit in the matching place, otherwise they are silently ignored.
59
What problems come up if you return an entity directly as a REST response (through Jackson)?
Jackson calls the getters and opens up lazy associations: you get either LazyInitializationException or a hidden N+1, and with a bidirectional association, infinite recursion. On top of that, your API contract gets tied to the database and internal fields leak out.
60
After `merge()`, why don't changes to the object you passed as the argument reach the database?
merge() does not make the detached object managed. It copies its state onto the managed copy in the persistence context and returns that copy. Later changes must be made on the returned object.
61
How do you detect and fix the N+1 problem in a real project?
If the SQL log or Hibernate statistics show a run of identical SELECTs after a single list query, that's N+1. The fix is to load the needed association with join fetch, an entity graph or batch fetching, or to switch to a DTO projection.
62
What happens if you `join fetch` a collection and paginate with `setMaxResults()` at the same time?
Hibernate doesn't put LIMIT in the SQL: it loads all the rows, paginates in memory, and logs the HHH90003004 warning. You don't notice it on a small table, but on a big one memory and time blow up.
63
When and how do you use `@EntityGraph` in Spring Data JPA?
To tell a repository method which lazy associations should be loaded together in that query. It gives the effect of join fetch without writing JPQL, and it also works with derived query methods.
64
Why is a query that returns a `Page` slow in Spring Data JPA, and how do you manage the count query?
Page sends two queries every time: one for the data and one for count(*). On a big table or a query with complex joins, the count can be more expensive than the data query. The fix is to write the countQuery separately and keep it simple, or to return a Slice if you don't need the total.
65
How do you enable audit fields like `@CreatedDate` and `@LastModifiedBy` in Spring Data JPA, and when do they stop working?
You need @EnableJpaAuditing, @EntityListeners(AuditingEntityListener.class) on the entity, and an AuditorAware bean that supplies the user. They work in JPA lifecycle callbacks, so the fields aren't updated for changes made through a bulk JPQL update, native SQL or StatelessSession.
66
When does Hibernate flush under `FlushMode.AUTO`, and how does that affect query results?
Before commit, and before a JPQL/HQL query that is affected by pending changes in the persistence context. That's why an entity you just persisted inside the transaction shows up in the result of the next query.
67
In Spring Data, after a bulk UPDATE with `@Modifying`, why do you still see the old values?
A bulk JPQL/SQL statement goes straight to the database and bypasses the persistence context. Entities that are already loaded stay in their old state. You need to clear the context with clearAutomatically = true or em.clear().
68
What can happen if you put `CascadeType.ALL` on the `@ManyToOne` side?
If you delete the child, the REMOVE cascade passes to the parent, and the parent entity is deleted. If it has other children, you get an FK error or, even worse, unexpected data loss. Cascade is normally set in the parent → child direction.
69
For inheritance, would you pick SINGLE_TABLE, JOINED or TABLE_PER_CLASS?
Most often SINGLE_TABLE: one table, no JOINs, fast polymorphic queries, but subclass columns have to be nullable. JOINED is normalized and allows NOT NULL, but every read needs a JOIN. TABLE_PER_CLASS does a UNION on polymorphic queries and is rarely chosen.
70
When are Spring Data's derived query methods (`findByStatusAndCreatedAtAfter`) convenient, and when is it better to write `@Query`?
For simple searches with two or three conditions, a derived method is convenient and is validated at startup. When the name gets long, or you need a join fetch, a projection or a complex condition, @Query (JPQL) or a Specification is easier to read and manage.
71
If a `@Transactional` method calls a `REQUIRES_NEW` method, what happens to the persistence context and the entities?
REQUIRES_NEW suspends the outer transaction and opens a new connection and a new persistence context. An entity loaded in the outer method is not managed in the inner transaction, and a change made inside doesn't show up on the copy in the outer context.
72
How do `@BatchSize` or `hibernate.default_batch_fetch_size` ease the N+1 problem?
Lazy associations are loaded in groups instead of one at a time: Hibernate sends a single where id in (?, ?, ...) query for several parents in the context. Instead of 100 SELECTs you get 2-3, and you don't have to rewrite the queries.
73
What settings do you need to speed up bulk INSERTs in Hibernate?
Turn on hibernate.jdbc.batch_size, group statements with order_inserts/order_updates, use SEQUENCE rather than IDENTITY for the id, and empty the persistence context with flush() + clear() every N records.
74
What is `@ElementCollection`, and when would you use it instead of a `@OneToMany` entity?
@ElementCollection is a set of values with no id of their own that belong only to the owner (tags, phone numbers). It's stored in a separate table, but its lifecycle is entirely tied to the owner. The downside: on a change, Hibernate often deletes all the rows and writes them again.
75
How do you write a composite primary key in Hibernate: `@EmbeddedId` or `@IdClass`?
Both work. With @EmbeddedId the key is a separate @Embeddable object (often a record), while with @IdClass the key fields sit separately in the entity. In both cases the key class must be Serializable and implement equals/hashCode correctly.
76
What is an `AttributeConverter` and when do you use it?
AttributeConverter<X, Y> converts a Java type to a database column type and back. It's handy for value objects (money, phone number), enums with custom codes, or simple encryption. It doesn't apply to @Id, @Version or associations.
77
How do you do soft delete in Hibernate 6?
Since Hibernate 6.4 there is @SoftDelete: remove() updates a flag column instead of running a DELETE, and the filter is added to queries automatically. The older way is @SQLDelete + @SQLRestriction (@Where up to Hibernate 6.3).
78
What does `@DynamicUpdate` do, and when does it make sense to turn it on?
By default Hibernate writes all of the entity's columns in an UPDATE. With @DynamicUpdate, only the changed columns go into the SQL. It helps with wide tables, large columns, and when two parallel transactions change different fields, but it can hurt the statement cache and batching.
79
I get a foreign key error when deleting an entity. How do you correctly organize deleting the related records?
The options: put CascadeType.REMOVE/orphanRemoval on the children collection, use ON DELETE CASCADE in the database (@OnDelete in Hibernate), or delete the children first with a bulk query. The choice depends on the number of children and on whether you need Java logic on deletion.
80
How does choosing `List`, `Set` or an ordered `List` (`@OrderColumn`) for an entity collection affect Hibernate's behavior?
A List without @OrderColumn is a "bag": duplicates are allowed, order isn't stored, and on a @ManyToMany removing one element often leads to deleting all the join rows and rewriting them. A Set deletes the exact row, and @OrderColumn stores the position in a separate column.
81
How does dirty checking work internally, and why does it get slow in a big persistence context?
On load, Hibernate stores a state array (snapshot) for each entity, and on flush it compares every field of every managed entity against that snapshot. With 50 thousand entities in the context, every flush means that many comparisons, plus double the memory.
82
What does `@Immutable` give you in Hibernate, and for which entities do you use it?
@Immutable makes an entity read-only: Hibernate sends no UPDATE for it, takes it out of dirty checking, and makes it fit the read-only cache strategy. It's good for reference data, views, and audit and event tables, but an attempt to modify it is often silently ignored.
83
What is stored inside Hibernate's second-level cache, and which concurrency strategy would you choose?
Not the entity objects but their "dehydrated" state: an array of field values keyed by id. The strategies are READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE and TRANSACTIONAL. The choice depends on how much the data changes and how much staleness you can tolerate.
84
If you turn on Hibernate's query cache, when does it do harm instead of good?
The query cache stores only the result ids, and any write to one of the tables in the query invalidates the whole result. On frequently changing tables the hit rate is low, and invalidation overhead and extra loads by id are added on top.
85
If you need to process a million rows through Hibernate, how do you avoid `OutOfMemoryError`?
Don't fetch everything with a single getResultList(): read in pieces with ScrollableResults or a stream, call flush()/clear() after every N rows, or use a StatelessSession, which has no persistence context. Even better, split the work into separate transactions by ID ranges.
86
How do `getClass()` and `instanceof` checks mislead you when working with a Hibernate proxy?
A lazy @ManyToOne field returns a subclass proxy that Hibernate generated, not the real class. getClass() gives the proxy class, and in an inheritance hierarchy the proxy is created for the parent type, so instanceof CardPayment can come out false.
87
How can `merge()` of a detached entity silently wipe out another user's change?
merge() copies all the fields of the detached object over the current state in the database. If there's no @Version, any change someone else made since you opened the form is overwritten with the old values: a lost update.
88
When several workers take tasks from one table, how do you use `PESSIMISTIC_WRITE` with `SKIP LOCKED`?
Each worker takes rows with select ... for update skip locked limit N: rows locked by other workers aren't waited for, just skipped. In Hibernate you do this with PESSIMISTIC_WRITE plus a lock timeout of -2 (LockOptions.SKIP_LOCKED).
89
Why is `@OneToOne(mappedBy, fetch = LAZY)` loaded like EAGER anyway, and what are the fixes?
The inverse (mappedBy) side has no FK, so Hibernate doesn't know whether the related row exists, and to choose between a proxy and null it has to run a SELECT. The fixes are a shared primary key with @MapsId, making the association unidirectional, or bytecode enhancement.
90
What happens if `allocationSize` in `@SequenceGenerator` doesn't match the database sequence's `INCREMENT BY`?
Hibernate's pooled optimizer treats the sequence value as a block boundary. With allocationSize = 50 and increment by 1 in the database, two instances or two sessions can land in each other's ranges, generate the same id, and fail with a duplicate key error.
91
Why does this code fail with a unique constraint error, even though the old row was deleted first?
At flush time Hibernate sends SQL in its own order, not the order you called things in: INSERTs first, then UPDATEs, and DELETEs at the very end. The new row is added before the old row is gone, and the unique index is violated.
92
How do you fix `LazyInitializationException` the right way, and why is `enable_lazy_load_no_trans` a bad solution?
The right way is to load the data you need explicitly inside the transaction: fetch join, entity graph, DTO projection. hibernate.enable_lazy_load_no_trans=true opens a new temporary session and connection for every lazy access, which hides N+1 and breaks isolation.
93
What does Hibernate bytecode enhancement give you, and what does it cost to turn on?
At build time the entity classes are modified: lazy basic attributes (for example, a large @Lob), a truly lazy @OneToMany on the mappedBy side of a @OneToOne, field-level dirty tracking, and automatic synchronization of associations. The cost is a build plugin, unexpected behavior when debugging, and differences in tests.
94
When moving from Hibernate 5 to 6 (Spring Boot 2 → 3), which changes hurt the most?
javax.persistence → jakarta.persistence, the new SQM query parser (HQL is validated more strictly), the rewrite of @Type/@TypeDef and the custom type API, and changes to the defaults for id generators and sequence naming. Result types and the behavior of some native queries differ as well.
95
What's the difference between giving an entity graph as a "fetch graph" and as a "load graph"?
With a fetch graph, the attributes listed in the graph are treated as EAGER and all the others as LAZY. With a load graph, the ones in the graph become EAGER, while the others keep the FetchType from their mapping.
96
In Hibernate 6, do you still need `select distinct` when you `join fetch` a collection?
To remove duplicates of the root entity, not anymore: Hibernate 6 does it itself. In Hibernate 5, distinct went into the SQL and also deduplicated in Java, so it was common to remove it from the SQL with the QueryHints.PASS_DISTINCT_THROUGH=false hint.
97
How do you write a search endpoint with many optional filters using Hibernate?
Instead of building JPQL by concatenating strings, I use the Criteria API or Spring Data's Specification on top of it: each filter is a separate predicate, and one that doesn't come in isn't added. In many complex cases I use a type-safe DSL (Querydsl, jOOQ) or combine it with a DTO projection.
98
What do you do when the parent entity's version must be incremented even if only a child entity changed?
You read the parent with LockModeType.OPTIMISTIC_FORCE_INCREMENT or call em.lock(parent, ...): Hibernate increments the parent's @Version even if the parent itself didn't change. That way the whole aggregate is protected by a single version.
99
Why does a unidirectional `@OneToMany` (without `mappedBy`) send more SQL than you'd expect?
Without @JoinColumn, Hibernate creates a separate join table. With @JoinColumn, it first INSERTs the child without the FK, then sets the FK with a separate UPDATE. As a result there are two statements per child, and making the FK column NOT NULL gets harder.
100
When you assign the id yourself (a UUID or an external code), why does Spring Data `save()` send a SELECT before every INSERT?
save() decides whether an entity is new by checking whether the id is null. If the id was assigned by hand, the entity is considered "existing", so merge() is called instead of persist(), and merge first looks for the row in the database.
101
Does Hibernate grab the connection as soon as a transaction starts, and what is the `provider_disables_autocommit` setting for?
Spring's JpaTransactionManager takes a connection at the start of the transaction and turns autoCommit off, even if the first SQL statement is still a long way off. If the pool already hands out connections with autoCommit=false, hibernate.connection.provider_disables_autocommit=true tells Hibernate so, which lets it delay acquiring the connection until the first query.
102
When do you need `EntityManager.refresh()`, and how does it differ from `find()`?
If the entity is already in the persistence context, find() returns that copy without going to the database. refresh() always runs a SELECT and overwrites the managed entity's state with the values in the database, so unsaved changes are lost. You need it after a trigger, a default value or a bulk update.
103
To send an event after an entity is saved, would you use `@PostPersist` or `@TransactionalEventListener`?
@PostPersist is called when the INSERT is executed or scheduled, but the transaction hasn't committed yet, so if it rolls back, the event has already gone out. @TransactionalEventListener(phase = AFTER_COMMIT) runs only after a successful commit, so it's the right place for external side effects (email, Kafka).
104
When you call `order.getCustomer().getId()`, does the lazy proxy get initialized, meaning does SQL go out?
No, usually it doesn't: the proxy holds the id itself and returns it from the identifier getter without initializing. Any other getter (getName()) does trigger a SELECT. This behavior is true only when a proxy is in use; if it came from find() or the association is EAGER, the full object is already loaded.
105
A comment can belong to several types of object (post, photo, video). How do you model such a polymorphic association in Hibernate?
There are three ways: Hibernate's @Any with a (target_type, target_id) pair, a separate nullable FK column for each type, or inheritance with a shared parent entity (Commentable). @Any is flexible but has no FK, so the database can't check data integrity. When the number of types is small, I prefer separate FK columns.
106
In a `JOINED` inheritance hierarchy, what SQL does an HQL bulk `delete` or `update` turn into?
Because one entity is split across several tables, Hibernate can't do the job in a single SQL statement. It first collects the matching ids into a temporary table (or a CTE, depending on the dialect), then deletes from each table separately. So such queries are slower than expected and produce more SQL.
107
Why does `offset` pagination slow down on a big table, and how do you do keyset (seek) pagination in Hibernate?
For OFFSET 100000 the database reads 100 thousand rows and throws them away, so the deeper the page, the slower it gets. With keyset you ask for the rows after the last value you saw: where (created_at, id) < (:lastTs, :lastId) order by created_at desc, id desc limit 20, which is always fast on an index.
108
If you call a Spring Data repository method from a service without `@Transactional`, what happens with the transaction and the persistence context?
The SimpleJpaRepository methods themselves carry @Transactional (reads are readOnly), so each call runs in its own short transaction. As a result, entities become detached between consecutive calls, changes aren't saved automatically, and lazy associations fail.
109
After Hibernate throws an exception, can you keep using the same `EntityManager`/`Session`?
No. According to the Hibernate documentation, after an exception in a Session you should roll back the transaction and close the Session, because the persistence context may be inconsistent with the database. In particular, after a ConstraintViolationException during flush, flushing again tries to send the same SQL again.
110
How do you do "update if it exists, insert if it doesn't" (upsert) correctly with Hibernate?
findById + save creates a race condition with parallel requests: both see "doesn't exist" and both INSERT. The reliable way is the database's own upsert (insert ... on conflict do update on PostgreSQL, merge on others) through a native query, or a unique constraint plus catching the error and retrying.
111
What SQL do Spring Data's `deleteAll()`, `deleteAllInBatch()` and `deleteByStatus()` run internally?
deleteAll() and the derived deleteBy... first load the entities and then send a separate DELETE for each one. Cascade and callbacks work, but it's slow. deleteAllInBatch() and @Modifying @Query("delete ...") delete with a single SQL statement, but bypass cascade, orphanRemoval and the persistence context.
112
How do you map a PostgreSQL array column (`text[]`, `bigint[]`) in Hibernate 6, and when is that a good idea?
Hibernate 6 supports arrays as a plain basic type: for a String[] or List<String> field you add @JdbcTypeCode(SqlTypes.ARRAY) if needed. It's convenient for small values like tags that are read only together with the owner. If you need joins or an FK on the elements, a separate table is better.
113
What happens if you pass 100 thousand ids to a `where id in (:ids)` query, and how do you write it in that case?
Each id becomes a separate bind parameter. On the PostgreSQL JDBC driver you hit the parameter count limit (roughly 32-65 thousand, depending on the driver) and it fails, and on Oracle an IN list can't exceed 1000 elements. On top of that, the plan cache bloats. The fix is to split into batches, use an array parameter (= any(?)) on PostgreSQL, or join against a temporary table.
114
If you can't add a `version` column to the table, how do you enable optimistic locking in Hibernate?
Hibernate has @OptimisticLocking(type = DIRTY) or ALL mode: the old values are added to the where part of the UPDATE instead of a version. DIRTY checks only the changed columns and works together with @DynamicUpdate. This is good for legacy schemas, but unreliable with a detached entity (merge).
115
What happens to unflushed changes when you call `em.clear()` or `em.detach()`?
They silently disappear. clear() and detach() remove entities from the context, and the pending INSERTs/UPDATEs are cancelled too. That's why in batch jobs the order is always flush() and then clear(); and in Spring Data, @Modifying(clearAutomatically = true) should be paired with flushAutomatically = true.
116
When a native `UPDATE` query runs, what does Hibernate do to the second-level cache?
Hibernate doesn't know which tables a native SQL statement touches, so to be safe it clears the entire L2 cache (all entity and collection regions). To avoid that, you tell it which entities are affected with NativeQuery.addSynchronizedEntityClass() or addSynchronizedQuerySpace().
117
What is the JPA static metamodel (`Order_`), and why use it when working with the Criteria API?
The static metamodel is an Order_ class that an annotation processor generates for each entity at compile time, with the attributes as typed constants. In Criteria you write Order_.status instead of the string "status": if a field name changes, the error shows up at compile time, not at runtime.
118
When a unique constraint is violated, how do you return a clear "this email is taken" message to the user?
The error doesn't appear at save() time but at flush or commit, and Spring wraps it in a DataIntegrityViolationException. I pull Hibernate's ConstraintViolationException out of it and pick the message by constraint name. An up-front existsBy check is useful, but it can't be the only defense because of races.
119
What is `StatelessSession` and when would you use it instead of a regular `Session`?
StatelessSession works without a persistence context: no snapshots, no dirty checking, no cascade, and no L1/L2 cache. Every insert/update turns into SQL right away, so memory stays steady and it's fast for big import and export jobs.
120
If you need raw JDBC inside a Hibernate session (`Session.doWork`), what do you watch out for with the transaction and flush?
doWork hands you the same connection Hibernate is using, so the work runs in that same transaction. But Hibernate doesn't know about the SQL you write: you need to flush() before it, and afterward the entities in the context may be stale. Don't close the connection and don't change auto-commit.
121
Can you join two entities in JPQL/HQL that have no association in the mapping?
Yes. Since Hibernate 5.1 there is the "entity join": join Payment p on p.orderNumber = o.number, and there doesn't have to be a @ManyToOne or @OneToMany. It lets you write report and verification queries without cluttering the mapping with extra associations.
122
Can you map a single FK column both as a `@ManyToOne` association and as a plain `Long customerId` field?
You can, but one of the two has to be read-only: usually @Column(insertable = false, updatable = false). Otherwise Hibernate fails at startup with a "column is duplicated in mapping" error. The read-only field is filled only on load: after persist() it stays null.
123
How does `@ManyToOne(optional = false)` differ from `@JoinColumn(nullable = false)`, and how does it affect the SQL?
nullable = false is mostly for DDL: it puts NOT NULL on the column. optional = false tells Hibernate the association is always present: it can use an inner join instead of a left outer join in joins, and it can check for a null value before flush. Writing both together is normal.
124
Does adding one element to a large lazy collection (`post.getComments().add(c)`) load the whole collection?
It depends on the collection type. For a List (bag) on the mappedBy side, Hibernate queues the add() and doesn't load the collection. A Set has to check for duplicates, so it usually initializes the whole collection. size(), contains() and iteration always load it.
125
Is an `EntityManager` injected into a Spring bean thread-safe? When is using it from several threads dangerous?
What gets injected with @PersistenceContext (or through the constructor in Spring Boot) is a shared proxy: on each call it routes to the real EntityManager bound to the current thread's transaction, so it's safe in a singleton. The real EntityManager and the entities in it are not thread-safe, though, and handing them to another thread is dangerous.
126
What SQL does a polymorphic query turn into under the `TABLE_PER_CLASS` strategy, and why can't you use it with an `IDENTITY` id?
Each concrete class stores all of its columns in its own table, so select from Base becomes a UNION ALL over the subclass tables. The id must be unique across all tables, while IDENTITY gives a separate counter in each table.
127
How do you map a database view or the result of a complex SQL query as a Hibernate entity?
I map a view as an ordinary @Entity + @Table(name = "view_name") and add @Immutable, so Hibernate doesn't try to write to it. If you can't create a view, Hibernate's @Subselect annotation makes the SQL itself the source of the entity; with @Synchronize you tell it which tables it depends on.
128
How do you automatically catch N+1 appearing in an integration test?
Count the SQL statements sent during the test through Hibernate Statistics or datasource-proxy, and assert against the expected value. Then if someone opens a lazy association inside a loop, the test fails right away.
129
Everything passes in a `@DataJpaTest` or `@Transactional` test, but on prod the same code fails with a constraint error. What could the cause be?
The test transaction is rolled back at the end, so a flush often never happens at all: the INSERT/UPDATE never reaches the database, and constraint, trigger and FK errors don't show up. Also, reads inside the test come from the persistence context, not the database. The fix is to flush() and clear() in the test, or to write the test without a transaction.
130
How do you limit long-running queries: how do the JPA query timeout, `@Transactional(timeout)` and the database's `statement_timeout` differ?
The jakarta.persistence.query.timeout hint sets a limit in milliseconds on a single query and works through JDBC setQueryTimeout. @Transactional(timeout) passes the time remaining in the whole transaction to each query as its timeout. PostgreSQL's statement_timeout is the last line of defense on the database side: it applies no matter what the application does.
131
How do `@Formula` and `@SQLRestriction` (formerly `@Where`) work in Hibernate, and what are their dangers?
@Formula computes a field from a SQL expression, and it is added to every select as a subquery. @SQLRestriction adds a SQL where condition every time the entity or collection is loaded; in Hibernate 6.3 @Where was deprecated and replaced by this name.
132
Which type is good for a `@Version` field: `int`, `Long` or `Instant`? Why does this choice matter for Spring Data?
A numeric version (Long, Integer) is reliable: it goes up by exactly one on every UPDATE. An Instant version depends on time precision, and two changes can get the same timestamp. Choose a wrapper type, not a primitive: Spring Data decides an entity is new by version == null.
133
How do you map PostgreSQL's native enum type in Hibernate 6, and when is it better or worse than `varchar` + a `check` constraint?
In PostgreSQL you create the type with create type ... as enum; in Hibernate 6 you put @Enumerated(EnumType.STRING) and @JdbcTypeCode(SqlTypes.NAMED_ENUM) on the field. The database rejects a wrong value itself and the value is stored compactly, but changing the enum in a migration is heavier than with varchar + check.
134
How do you map a JSON column in Hibernate 6, and what's better about it than an `AttributeConverter`?
In Hibernate 6, if you put @JdbcTypeCode(SqlTypes.JSON), the field (Map, record, POJO) is converted to JSON through Jackson and written to jsonb on PostgreSQL. Unlike a converter, Hibernate understands the type, dirty checking works correctly, and in 6.2+ if you map an @Embeddable type as JSON, you can reach its fields in HQL.
135
How does database-level column encryption with `@ColumnTransformer` (for example, pgcrypto) work, and what are its limitations?
@ColumnTransformer wraps the column in a SQL expression on read and write: pgp_sym_encrypt(?, key) when writing, pgp_sym_decrypt(column, key) when reading. The entity keeps a plain String. But you can't search an encrypted column with an index, the key travels through the SQL, and native queries don't know about this transformation.
136
You suddenly need an extra column (for example, `added_at` or `role`) on a `@ManyToMany` join table. How do you change the mapping?
@ManyToMany can't express an extra column. You have to make the join table its own entity (ProjectMember) and link it from both sides with @ManyToOne. Both parent entities keep an @OneToMany(mappedBy = ...) collection. A data migration usually isn't needed, because the table is the same.
137
Why aren't the changes saved to the database in a `@Transactional` method called through `this.save()` inside a service?
@Transactional works through the Spring proxy. If the method is called from inside the same class through this, the proxy is bypassed and no transaction is opened. Without a persistence context there's no dirty checking either, so changing a loaded entity saves nothing.
138
What is Hibernate's `StatementInspector`, and what practical purposes do you use it for?
StatementInspector is a hook Hibernate calls before sending each SQL statement to JDBC: it receives the SQL string and returns a (modified) string. I use it to add a trace id or endpoint name to a query as a comment, to count queries in tests, and to catch dangerous SQL. Not for changing the meaning of the SQL.
139
When does the "detached entity passed to persist" error occur, and how do you fix it?
When you pass persist() an object that has an id set but isn't in the context: Hibernate considers it detached. It often appears through cascade PERSIST, when a child that already exists in the database (say, one that came in the request with an id) is passed along with a new parent.
140
Why does the "object references an unsaved transient instance" error appear when you save while linking a new object to a `@ManyToOne`?
The linked object is transient: it isn't in the database and Hibernate doesn't know it, and no cascade is set. At flush, Hibernate can't find an id for the FK and throws TransientPropertyValueException. If you need to link to a record that's in the database, use getReferenceById(); if it's new, persist() it first.
141
For an ingestion service that receives thousands of records per second, do you stay on Hibernate or move to JDBC/jOOQ? How do you decide?
I measure first: with SEQUENCE + batch_size + order_inserts + driver rewrite, Hibernate handles a lot of load. If the profile shows the cost of the persistence context, hydration and dirty checking, or if I need upsert/COPY, I move only that write path to JDBC, and the rest of the domain stays on Hibernate.
142
How do you set up Hibernate's second-level cache in an application with several instances, and what consistency problems should you be ready for?
If each instance has a local cache, a change written on one node isn't visible on another. The options are a local cache with invalidation messages (Infinispan invalidation mode), a distributed cache (Hazelcast, JCache over Redis), or using L2 only for immutable data.
143
To decrement warehouse stock (high contention), how do you choose between optimistic and pessimistic locking?
If conflicts are rare, optimistic (@Version + retry): no lock is held. If many writers hit one row (a popular product, a promotion), optimistic turns into a retry storm; then a pessimistic lock or an atomic SQL update ... set qty = qty - ? where qty >= ? is more reliable.
144
A user keeps a form open for 10 minutes and then saves. How do you prevent a "lost update" across several HTTP requests?
I give the version to the client (a DTO field or an ETag), and it comes back with the save. The server loads the entity, compares the incoming version with the current one, and returns 409 if they don't match. I don't keep the persistence context alive between requests.
145
Compare the separate-schema, separate-database and `@TenantId` (discriminator) approaches to multi-tenancy in Hibernate 6.
@TenantId puts a tenant_id column in a single table and Hibernate does the filtering itself; it's cheap and suits many tenants, but isolation is the weakest. Separating by schema or database strengthens isolation, but migrations, connection pools and operational cost grow with the number of tenants.
146
A report endpoint that loads a huge number of entities has increased GC pauses. How do you reduce memory on the Hibernate side?
For every managed entity, Hibernate holds the entity itself, the snapshot, the EntityEntry and the collection wrappers. For a report, a DTO projection instead of entities, a read-only hint, cursor-based reading and, if needed, aggregating at the SQL level cut memory several times over.
147
On prod, one endpoint slows down from time to time and suspicion falls on Hibernate. How do you diagnose it?
First I isolate which part is slow: the number of SQL statements (N+1), a single slow query, connection waits, or flush/hydration. For that I use a trace (OpenTelemetry), a datasource-proxy or p6spy log, Hibernate statistics, HikariCP metrics and the database's slow query log together.
148
In a domain model, entities are linked to each other with a lot of `@OneToMany` and cascade. How do you carry aggregate boundaries into the Hibernate mapping?
I keep cascade and collections only inside a single aggregate: the root manages its own children, and I refer to other aggregates by id, not by object. That sharply reduces the size of the graph, the scope of locks, and accidental cascade mistakes.
149
How do you rename a column with zero downtime in a table used by a Hibernate entity?
You can't rename it in one go, because during a deploy the old and new versions run together. Expand-contract: add the new column, write to both, migrate the data, switch reads to the new one, and drop the old column only in the last release. Flyway manages the schema and Hibernate only does validate.
150
How do you use read replicas with Hibernate, and how do you prevent the errors caused by replication lag?
With AbstractRoutingDataSource + LazyConnectionDataSourceProxy I send read-only transactions to the replica and the rest to the primary. For "I wrote it but I can't see it" cases caused by lag, I keep reads right after a write on the primary and use the L2 cache carefully.
151
You need to write several million rows to the database fast through Hibernate. How do you approach it?
I turn on JDBC batching, use a (pooled) sequence for IDs, flush/clear every N rows, or switch to StatelessSession. At really large volumes, COPY or a native bulk insert is faster still.
152
OptimisticLockException keeps showing up on prod. How do you analyze it, and how do you design the retry?
First I find out which entity and which threads are colliding. The retry has to rerun the whole transaction with a fresh persistence context, a limited number of attempts and jitter; if it's a hot row, the model has to change.
153
How do you make Hibernate lighter on read-only queries?
I mark the transaction readOnly, so Hibernate keeps no snapshots and does not flush. Where possible I return a DTO projection instead of an entity, because it never enters the persistence context at all.
154
This code puts a Hibernate entity into Spring Cache. What problems come up, and how would you rewrite it?
What lands in the cache is a managed entity: on later requests it is detached, its lazy associations throw LazyInitializationException, one object ends up shared across threads, and if anyone modifies it, everyone is affected. The cache should hold an immutable DTO (a record), not an entity.
155
Which entities should go into the second-level cache and which should not? How do you decide?
Entities that are read a lot, change rarely and are written only through this application: reference data, settings, catalogs. I don't cache anything that changes fast, that other systems also write to, or that involves money.
156
How do long-open transactions hurt the database in a Hibernate service, and how do you find them?
A long transaction holds a connection, keeps the locks it took, and on PostgreSQL stops VACUUM from cleaning up old row versions, so tables and indexes bloat. To find them I watch xact_start and the idle in transaction state in pg_stat_activity, Hikari's leak detection, and transaction times in the APM.
157
How do you design the Hibernate mapping and database columns for a domain that deals with money amounts and currencies?
BigDecimal in Java (or a long in minor units), numeric(precision, scale) in the database, never double/float. An amount and its currency travel together, so I make an @Embeddable Money(amount, currency). The rounding rule lives in one place, and the scale is set explicitly per currency.
158
How do you do soft delete in Hibernate, and where does it cause problems?
Hibernate 6.4+ has the @SoftDelete annotation; before that the @SQLDelete and @SQLRestriction pair was used. Problems: unique indexes, native queries, cascades and the table growing without bound.
159
What safeguards do you put in the team so the N+1 problem doesn't keep coming back to prod?
In integration tests I assert the number of SQL queries for every important endpoint, in dev the Hibernate statistics and slow query log are on, and open-in-view is off. That way, even if an N+1 slips through code review, the test fails.
160
Which indexes does your Hibernate mapping call for, and how do you find the missing ones?
Neither Hibernate nor PostgreSQL creates an index on foreign key columns automatically, yet every lazy load and collection read does a where on exactly that column. So every @ManyToOne FK, frequently used filter+sort combinations and unique business keys need an index. I find the missing ones with pg_stat_statements, EXPLAIN and a query that checks the FKs.
161
Would you standardize JPA/Hibernate across all services in the company, or jOOQ/plain SQL? What criteria do you decide by?
I don't force a single standard. Hibernate pays off in services with a rich domain and lots of CRUD; in services with complex reporting, high-volume writes and work close to SQL, jOOQ or JDBC is better. What matters is that the team's experience and the observability tooling are the same.
162
You need to split the shared Hibernate domain model of a monolith into several services. How do you cut the associations between entities?
First I draw module boundaries inside the monolith and replace the @ManyToOne/@OneToMany associations that cross a boundary with id fields. Cross-module joins become data fetched through an API call or an event. I split the database in stages too: first a separate schema and ownership, then a separate database.
163
In a big team, how do you establish a rule for how entities, DTOs and API models move between layers?
Entities never leave the persistence and domain layers: controllers and the external API work only with DTOs/records, and mapping happens inside the transaction, at the service boundary. I enforce the rule not with a document but with ArchUnit tests, a shared mapper approach and a code review checklist.
164
You plan to use UUIDs as primary keys. How do you choose between UUIDv4 and UUIDv7, and how do you set it up in Hibernate?
UUIDv4 is random, so it writes to the B-tree index all over the place and slows down on large tables. Time-ordered UUIDv7 almost eliminates that problem. Hibernate 6 has @UuidGenerator(style = TIME), but it is not v7, so for v7 you often need your own generator.
165
How do you plan moving Hibernate-based services from one database to another (say, from Oracle to PostgreSQL)?
Hibernate gives you only part of the portability: JPQL and mappings carry over, but native SQL, sequence/identity, types (NUMBER, CLOB, dates), case sensitivity and transaction behavior do not. The plan: an inventory, tests against both databases, data migration (kept in sync with CDC), gradual traffic cutover and a way back.
166
Should the company build a shared "persistence starter" library (base entity, auditing, Hibernate settings)? What are the risks?
For settings and small infrastructure, yes: safe defaults (open-in-view=false, batching, slow query log, metrics), an audit listener and test helpers. But a shared base entity hierarchy, a mandatory id strategy or "magic" interceptors tie services to each other and make upgrades harder.
167
A client retries a request after a network error. How do you prevent duplicate rows and operations executed twice in a Hibernate-based service?
The database has to guarantee idempotency: a unique constraint on the idempotency key the client sends (or on a business key), store the first result and return it for the repeated request. Just "check first, then write" (existsBy + save) does not work with parallel retries.
168
When does it pay off to do CQRS-style writes with Hibernate entities and handle the read side differently?
When read needs differ sharply from the write model: lists, filters and reports that join many tables. Writes go through entities and invariants, while reads go through DTO projections, SQL views or a separate read database.
169
How do you make sending an event to Kafka reliable alongside a Hibernate transaction? Explain the transactional outbox.
I don't send the event to Kafka directly; I write it to an outbox table in the same transaction. A separate relay (polling or Debezium CDC) reads the outbox and sends to Kafka. That way either both the data and the event are saved, or neither is.
170
On a high-load service, how do you design connection pool size, transaction length and Hibernate settings together?
The pool should be small: usually close to the database's core count, divided by the number of service instances. I keep transactions short, turn off open-in-view and make no external calls inside a transaction, otherwise the pool runs out at any size.
171
In Spring Boot open-in-view is on by default. How do you justify turning it off across the whole organization?
OSIV stretches lazy loading out to the view and serialization: connections stay busy longer, N+1 gets hidden, and SQL runs outside a transaction. Turning it off is painful, but it surfaces the problems instead of hiding them, so I make the default false in new services.
172
In a Hibernate-based system that stores personal data (passport, phone, address), how do you design the persistence layer: encryption, right to erasure, logs?
First I map out which data lives where and move the personal fields into a separate table or columns. I encrypt the necessary fields at the application level (keys in a KMS), add a blind index for searching, design an anonymization path for deletion, and close the leaks through SQL parameter logs, the L2 cache and backups.
173
Service traffic is expected to grow 10x in a year. What breaks first in the Hibernate and database layer, and how do you plan capacity?
Usually the connection pool and the CPU/IO of the single writer database fill up first, then N+1 and unindexed queries, large tables and lock contention show up. I start planning from current measurements: query count and database time per endpoint, then I use load tests to find which resource saturates first.
174
Two parallel transactions occasionally hit a deadlock with this code. What is the cause, and how do you prevent it at the system level?
Each transaction locks the rows in a different order: one A then B, the other B then A. Hibernate's flush order depends on the access order. The fix is to make the lock order stable: sort by ID, order_updates, or lock the needed rows up front in a defined order.
175
What can go wrong after this bulk UPDATE, and what rule do you set in the team for such queries?
A bulk JPQL goes straight to the database: entities in the persistence context and the L2 cache go stale, @Version does not increase, and entity listeners do not run. The rule: clear the context after a bulk operation, and keep such methods separate and documented.
176
Draw up a plan for migrating a large project from Spring Boot 2 / Hibernate 5 to Spring Boot 3 / Hibernate 6. Where will unexpected breakages happen?
The javax to jakarta move is the mechanical part. The real risk is in Hibernate 6's internal changes: sequence naming, the type system, JPQL semantics, result deduplication and removed APIs. That is why you need SQL-level regression tests and a staged release.
177
When should you not map a @OneToMany collection on the entity at all?
When the collection can grow without bound (orders, logs, payments), when it is not part of the aggregate, or when it is only read page by page. In those cases the association exists only on the child side as @ManyToOne, and the list is fetched through a repository query.
178
In a system where the entity hierarchy grows over the years, how do you choose the inheritance strategy, and how hard is it to change later?
Lots of polymorphic queries and similar subclasses: SINGLE_TABLE; large subclasses used on their own: JOINED; no polymorphic queries: @MappedSuperclass. Changing it later requires a data migration.
179
You need to keep a history of data changes. How do you choose between Hibernate Envers, CDC (Debezium) and DB triggers?
Envers gives a convenient entity-level history inside the application, but only sees changes that went through Hibernate. CDC captures any change in the database and is independent of the service. Triggers are the most reliable, but the logic stays in the database and is hard to observe.
180
The data now has to be split across several shards. What breaks in a service built with Hibernate, and how do you approach it?
Hibernate assumes one logical database: joins, transactions, sequences and polymorphic queries do not work across shards. I tie the shard key to the aggregate ID and design so that every transaction stays inside one shard; routing happens at the DataSource level.
181
A batch job that processes 20 million records every night is written with Hibernate and keeps dying with OOM. How do you redesign it?
I split the job into chunks: each chunk is its own transaction, reading with keyset pagination, and a clear at the end of the chunk. ScrollableResults or a DTO projection for reading, JDBC batch or StatelessSession for writing. Progress is saved so the job can be restarted.
182
When moving to Java 21 virtual threads, what do you pay attention to in the Hibernate and JDBC layer?
Virtual threads don't make the database faster: the real limit is still the connection pool. Blocking I/O inside synchronized can pin the carrier thread (before Java 24), so I check driver and pool versions and treat the pool as a semaphore.
183
For a new high-load service, how do you choose between blocking JPA/Hibernate, Hibernate Reactive and R2DBC?
In most cases blocking Hibernate + virtual threads is enough and the simplest for the team. The reactive stack only pays off when the whole service is reactive (WebFlux, streaming, thousands of open connections); Hibernate Reactive keeps the ORM convenience, while R2DBC is much lower level.
184
Which metrics and logs do you make mandatory for watching the Hibernate layer on prod?
Query duration and the number of queries per request, connection pool state (active, pending, acquire time), the slow query log, L2 cache hit/miss, and the count of optimistic lock failures. Hibernate statistics are turned on carefully on prod, through Micrometer.
185
On prod, the Hibernate query plan cache has taken a large part of the heap. What could be the cause, and how do you fix it?
Usually IN lists of varying length, or values concatenated into the query text, so a new query text is generated every time and lands in the cache. Writing with parameters, turning on in_clause_parameter_padding and limiting the cache size all help.
186
How reasonable is it to add system-wide logic (audit fields, tenant, encryption) through a Hibernate Interceptor or event listener? What are the risks?
It is right for small, mechanical jobs: filling createdAt/updatedBy, setting the tenant ID. I don't put business logic there: it is invisible, does not run for bulk and native SQL, executes during flush and can cause extra queries or a recursive flush.
187
Some column values are set by the database itself (triggers, DEFAULT, generated columns). How do you work with that in Hibernate, and where are the traps?
Hibernate doesn't know what happened in the database: after the INSERT the entity keeps an old or null value. If I mark the column with @Generated (Hibernate 6), Hibernate re-reads the value after the write. Every such column costs an extra SELECT or a RETURNING.
188
In Hibernate 6, when is using JSON columns the right call, and when is a normalized table better?
JSON is convenient for data whose schema changes fast, that is read as a whole and rarely filtered: settings, integration payloads, type-specific attributes. If you need joins, constraints, aggregation or frequent UPDATEs on it, use separate columns and tables.
189
Draw up a test strategy for the persistence layer for a team: H2, Testcontainers, slice tests and checking query counts.
The main test database is Testcontainers with the same database as prod. @DataJpaTest slice tests for mapping and queries, @SpringBootTest for a small number of full scenarios. The SQL count is asserted on important endpoints. H2 is only for very fast tests that don't depend on the database, or not at all.
190
One service has to write to two different databases through Hibernate (say, the main PostgreSQL and a separate reporting database). How do you organize the configuration and transactions?
A separate DataSource, EntityManagerFactory and TransactionManager for each database, with entity and repository packages clearly separated. I assume there is no atomic write to both databases: the write to the second one goes through an outbox or an async job, idempotently.
191
What checklist do you give the team for reviewing a PR with JPA entities?
I check the fetch type (everything LAZY), whether cascade and orphanRemoval are justified, whether equals/hashCode/toString are safe, whether ID generation works with batching, whether there is a @Version, whether it matches the migration, and whether the new queries bring an N+1 or pagination problem.
192
Two microservices write to the same tables in one database through their own Hibernate entities. What problems does this cause, and how do you get out of it?
Each service's cache and validation know nothing about the other's writes, nobody can change the schema independently, and version agreements break down. The way out is to assign a table owner; everyone else works through an API or events.
193
While saving an order you have to send an HTTP request to an external payment provider. How do you design the transaction boundaries?
I don't make the external call inside a database transaction. I split the process into states: first save in PENDING and commit, then make the payment call without a transaction, then write the result in a new short transaction. For failures there is an idempotency key and a reconciliation job.
194
What does @NaturalId give you, and how do you use it for entities that are frequently looked up by a business key?
@NaturalId tells Hibernate about the business key (tax ID, email, SKU): it is marked as unique and usually immutable, loaded with the Session's byNaturalId API, and the natural id → PK mapping is cached. That way repeated lookups hit the database less.
195
How do you balance database-specific features (stored procedures, window functions, partial indexes, LISTEN/NOTIFY) against Hibernate's portability?
Portability is often a false goal: switching databases rarely happens, but giving up the database's strengths costs money every day. I use database-specific features, but I gather them in a clear place, the repository layer and migrations, and run the tests on the real database.
196
A query sent by Hibernate takes 2 seconds in the application, but when you run the same SQL by hand in psql it takes 20 ms. How do you analyze it?
The difference is usually not in the SQL but in the conditions: bind parameter types and the generic plan, an implicit type conversion killing the index, the fetch size, or the time not being in the SQL at all but in turning the result into entities. I measure each one separately.
197
You want to build a GraphQL API on top of JPA entities. What problems come up with N+1 and control over loading, and how do you structure the architecture?
In GraphQL the client chooses the query shape, so each field resolver calls lazy loading and multiplies the N+1. I don't rely on the entity graph in resolvers: associations are batched by IDs through a DataLoader, and depth and complexity are limited.
198
This code runs at the READ COMMITTED isolation level. What happens if two doctors go off duty at the same time, and how do you fix it?
This is write skew: both transactions read "there are 2 people on duty" and each changes a different row, so nobody is left. An optimistic lock doesn't help, because the same row is not being changed. The fix is to lock a shared row, use SERIALIZABLE isolation, or a database constraint.
199
To show rows depending on the user's permissions: Hibernate @Filter or database-level Row Level Security, which do you choose?
@Filter is convenient and lives inside the application, but forgetting to enable it, native SQL and a direct find by ID all bypass it. If the security requirement is serious, I make PostgreSQL RLS the main protection, and @Filter or @TenantId stays as a convenience layer.
200
For an event or transaction table that collects billions of rows a year, how do you design the Hibernate entity and the database?
I partition the table by time, add the partition key to the primary key, and make the entity light for writing and often immutable. Old partitions are dropped or archived; reads mostly use projections and a time range.
Sign up — studied questions get marked and your progress is saved.