Interview
JDBC, JPA & Hibernate — Interview Questions (82+)
See `pkg11jdbc`.
Detailed Questions
1. JDBC core steps?
- Short: Load driver → get Connection → create Statement/PreparedStatement → execute → process ResultSet → close.
- Detailed: Modern JDBC 4+ auto-loads drivers. Always use try-with-resources.
PreparedStatementbinds parameters (prevents SQL injection, enables plan cache).ResultSetcursor over rows. - Example:
jdbc2JdbcBasicsin pkg11jdbc.
2. Statement vs PreparedStatement vs CallableStatement?
- Short: Statement static SQL; Prepared parameterized; Callable stored procedures.
- Detailed: Never concatenate user input into Statement.
setString(1, x)binds safely. CallableregisterOutParameterfor OUT params. - Example:
SELECT * FROM users WHERE id = ?
3. Connection pooling why?
- Short: Creating TCP+auth connections is expensive; pool reuses them.
- Detailed: HikariCP tracks idle, max pool size, connection timeout, leak detection. Size pool from DB max connections / app instances. Without pool, latency and DB overload under load.
- Example:
jdbc5ConnectionPooling.java.
4. Transaction management in JDBC?
- Short:
setAutoCommit(false), work,commit()orrollback(). - Detailed: One connection per transaction typically. Isolation levels
READ_COMMITTED,REPEATABLE_READ,SERIALIZABLE. Spring@Transactionalautomates this. - Example: Transfer money: debit + credit in one transaction.
5. JPA vs Hibernate vs JDBC?
- Short: JDBC low-level SQL; JPA spec/API; Hibernate JPA implementation + extras.
- Detailed: JPA maps entities to tables (
@Entity,@Table). Hibernate provides Session API, caching, dialects. JDBC when you need full SQL control or bulk ops. - Example:
EntityManager.persist(user)vsjdbcTemplate.update(...).
6. EntityManager vs Session?
- Short:
EntityManageris JPA standard;Sessionis Hibernate native extension of same idea. - Detailed: In Hibernate,
sessionFactory.getCurrentSession()integrates with transactions.EntityManagerfromEntityManagerFactory. Persistence context holds managed entities. - Example:
em.find(User.class, id)— first-level cache hit if managed.
7. Entity lifecycle states?
- Short: New/transient, managed/persistent, detached, removed.
- Detailed:
persist→ managed.closeEM → detached.mergereattaches detached copy.removeschedules delete on flush. Changes to managed entities auto-dirty-checked on flush. - Example: Modify managed
user.setName()— SQL UPDATE on commit without explicit update call.
8. Lazy vs eager loading?
- Short:
FetchType.LAZYloads association on access;EAGERloads immediately. - Detailed: Default
@ManyToOneeager,@OneToManylazy. Lazy needs open persistence context (or fetch join). Eager causes cartesian product / over-fetching. - Example:
user.getOrders().size()triggers lazy load if session open.
9. N+1 query problem?
- Short: One query for parents + N queries for each child association.
- Detailed: Loading 100 users then lazy-loading each user's orders = 101 queries. Fix:
JOIN FETCH,@EntityGraph, batch fetching (@BatchSize), or DTO projection query. - Example:
SELECT u FROM User u JOIN FETCH u.orders
10. First vs second level cache?
- Short: L1 = persistence context per EM/session; L2 = shared session factory cache (entities).
- Detailed: L1 always on for managed entities. L2 needs provider config (Ehcache, Infinispan); cache entity by id across sessions. Query cache separate. Stale data risk — tune TTL and invalidation.
- Example:
findby same id twice in one tx — one SELECT (L1).
11. JPQL vs native SQL?
- Short: JPQL object-oriented (
SELECT u FROM User u); native SQL database-specific. - Detailed: JPQL uses entity names and fields. Native for reporting, bulk, DB-specific features.
createNativeQuerymaps to entities or scalars. - Example:
em.createQuery("SELECT u FROM User u WHERE u.active = true").
12. Optimistic vs pessimistic locking?
- Short: Optimistic
@Versioncolumn check on update; pessimisticSELECT FOR UPDATElocks row. - Detailed: Optimistic good for low contention —
OptimisticLockExceptionon conflict. PessimisticLockModeType.PESSIMISTIC_WRITEholds DB lock during transaction. - Example:
@Version Long versionincremented each update.
Rapid-Fire (Q → A)
- DriverManager vs DataSource? → DataSource preferred with pool.
- SQLException checked? → Yes in raw JDBC.
- SQL injection fix? → PreparedStatement bind params.
- setObject? → Generic parameter binding.
- executeQuery vs executeUpdate? → SELECT vs DML.
- Generated keys? → Statement.RETURN_GENERATED_KEYS.
- Batch update? → addBatch executeBatch.
- Fetch size ResultSet? → Hints driver batch fetch.
- Scrollable ResultSet? → TYPE_SCROLL_INSENSITIVE.
- holdability? → CLOSE_CURSORS_AT_COMMIT.
- savepoint? → Partial rollback.
- Isolation READ_UNCOMMITTED? → Dirty reads possible.
- READ_COMMITTED default? → Many DBs default.
- REPEATABLE_READ? → Same row reads consistent.
- SERIALIZABLE? → Strictest; phantom risk reduced.
- Phantom read? → New rows appear in range.
- Dirty read? → Uncommitted data seen.
- Non-repeatable read? → Row changes between reads.
- ACID? → Atomicity, Consistency, Isolation, Durability.
- CAP in databases? → Consistency, Availability, Partition tolerance.
- @Entity required? → JPA managed class marker.
- @Id? → Primary key.
- @GeneratedValue strategies? → IDENTITY, SEQUENCE, TABLE, AUTO.
- @Column? → Name, nullable, length mapping.
- @Transient? → Not persisted field.
- @Embeddable? → Value type in entity.
- @EmbeddedId? → Composite key embed.
- @ManyToOne join column? → FK column.
- @OneToMany mappedBy? → Inverse side of bidirectional.
- CascadeType ALL? → Propagate persist/remove etc.
- orphanRemoval? → Delete children removed from collection.
- @JoinTable? → Many-to-many link table.
- equals/hashCode JPA? → Business key or id; avoid collections.
- toString JPA? → Avoid lazy collections in toString.
- ddl-auto none? → Production use migrations.
- ddl-auto validate? → Schema matches entities only.
- Flyway version table? → flyway_schema_history.
- Liquibase changelog? → XML/YAML changesets.
- Persistence unit? → persistence.xml config (less in Boot).
- EntityManagerFactory scope? → One per app typically.
- Thread-local session pattern? → Hibernate classic per thread.
- Stateless session? → Bulk ops no cache.
- getReference vs find? → Lazy proxy vs immediate load.
- persist vs merge? → New vs detached reattach.
- flush mode AUTO? → Flush before query/commit.
- COMMIT flush mode? → Flush only on commit.
- @Modifying query? → Update/delete JPQL needs @Transactional.
- clearAutomatically? → Clear persistence context after bulk.
- Pagination JPA? → setFirstResult setMaxResults.
- Page Spring Data? → Pageable Page
return. - Sort Spring Data? → Sort.by("name").
- Specification? → Predicate builder dynamic where.
- Criteria API Root? → From clause entity.
- Metamodel _ class? → Generated static fields for attrs.
- Hibernate @SQLRestriction? → Filter clause on entity.
- @Filter? → Dynamic enable/disable filter.
- @Formula? → Derived column read-only.
- @SecondaryTable? → Extra table mapping.
- Inheritance SINGLE_TABLE? → Discriminator column.
- JOINED strategy? → Table per subclass normalized.
- TABLE_PER_CLASS? → Table per concrete class.
- @MappedSuperclass? → Shared fields not entity.
- AttributeConverter? → Custom type DB mapping.
- JSON column mapping? → Hibernate Types / converter.
- Envers auditing? → Hibernate revision tables.
- Interceptor? → Hibernate callbacks low-level.
- Event listener? → JPA @PrePersist etc.
- @PreUpdate? → Before update SQL.
- Bean Validation @Email on entity? → Validates before persist.
- Schema multitenancy? → Separate schema per tenant.