Top JDBC Interview Questions and Answers
1. What is JDBC?
JDBC (Java Database Connectivity) is an API that enables Java applications to connect and
interact with relational databases using SQL queries.
2. Explain JDBC Architecture.
JDBC has four layers: java Application, JDBC API, JDBC Drivers and Database.
* The java Application is used to create a source file.
* The JDBC API is set of classes and interface. Which provides interfaces like Connection,
Statement, ResultSet, while JDBC API which will transfer the data to drivers.
* Then driver handles communication with the [Link] converting java calls to sql calls.
* The Database will help to store the data in relation model (column and rows).
3. Steps to connect to a database using JDBC.
1. Load the driver
2. Establish a connection
3. Create Statement
4. Execute query
5. Close the connection.
4. What is a JDBC Driver? Types?
A JDBC driver enables Java to communicate with a database.
Types:
JDBC-ODBC Bridge Driver (Type-1)
Converts JDBC calls into ODBC calls, requiring ODBC installation on the system.
Native-API Driver (Type-2, Partially Java)
Uses database-specific native libraries (like C/C++) to convert JDBC calls to DB-specific
calls.
Network Protocol Driver (Type-3, Fully Java)
Sends JDBC requests to a middleware server which communicates with the database.
Thin Driver (Type-4, Fully Java) (most use)
Communicates directly with the database. The thin driver converts JDBC calls directly into
the specific database protocol.
5. Difference between Statement and PreparedStatement.
We have 3 types of Statement:
[Link] which is use to executes static queries.
2. PreparedStatement which is use to executes precompiled queries with parameters
(dynamic queries), is faster, and prevents SQL injection.
[Link] which is use to execute stored queries from the procedures.
6. What is ResultSet? Types?
A ResultSet in Java is an object that holds the data retrieved from a database query
(typically a SELECT statement). It acts like a table of results, allowing you to iterate through
rows and access column values. You create it via
a Statement or PreparedStatement object's executeQuery () method.
ResultSet stores data from SELECT queries.
7. What is Connection Pooling?
Reusing DB connections instead of creating new ones. Improves performance. Examples:
HikariCP, C3P0.
8. What is Auto-Commit in JDBC?
Auto-commit automatically commits each SQL statement. It can be disabled using
setAutoCommit(false).
9. What are Batch Updates?
Executing multiple SQL statements in a single batch to reduce network calls.
10. How to prevent SQL Injection?
Use PreparedStatement instead of Statement.
11. Difference between execute(), executeQuery(), executeUpdate().
executeQuery() handles SELECT and returns ResultSet. executeUpdate() handles
INSERT/UPDATE/DELETE. execute() handles any SQL.
12. What is DriverManager?
A class that manages JDBC drivers and creates database connections.
13. What is CallableStatement?
Used to execute stored procedures.
14. What is Metadata in JDBC?
DatabaseMetaData and ResultSetMetaData provide information about database structure.
15. What is Transaction Management?
Controlling SQL operations as a single unit using commit or rollback.
16. Can JDBC be used with NoSQL?
No, JDBC is only for relational databases.
17. How to handle JDBC exceptions?
Using try-catch-finally or try-with-resources.
18. Role of [Link]()?
Loads the JDBC driver class.
19. JDBC vs Hibernate.
JDBC requires manual SQL, Hibernate automates and supports ORM.
20. Can stored procedures be called in JDBC?
Yes, using Callable Statement.
Servlet
[Link] is a Servlet?
A servlet is a Java program that runs on a server and handles HTTP requests and responses.
[Link] Lifecycle
Load the class. create an object.
Init (): Initializes servlet
service (): Handles request processing
destroy (): Cleans up before removal.
[Link] of Servlets
GenericServlet: Protocol-independent
HttpServlet: Handles HTTP requests.
[Link] Methods
doGe (): Handles GET requests (to get the data)
doPost (): Handles POST requests (to save the data)
doPut (): Handles Put requests (to update the data)
doDelete (): Handles Delete requests (to delete the data)
doPatch (): Handles Patch requests (to update the data)
[Link] & Response
HttpServletRequest is used to read data,
HttpServletResponse is used to send data back.
[Link] Configuration
Maps servlets to URL patterns.
[Link] Annotation
@WebServlet is used to configure servlet without [Link].
[Link]-param / ServletConfig
Used to pass configuration values to a specific servlet.
[Link]
Global configuration shared across the entire application.
[Link]
Used to forward or include resources.
[Link]
Redirects client to a new URL.
12.1Session Management
Tracks user data using Cookies, HttpSession, URL rewriting.
[Link]
Stores data in user's browser.
[Link]
Used for logging, authentication, and validation.
[Link]
Used to track events like session creation, context initialization.
16.1MVC Using Servlet
Servlet = Controller, JSP = View, DAO = Model.
[Link] Handling
Handled using try/catch or [Link] error-page.
[Link]
Fast, secure, platform-independent, supports multiple technologies.
[Link]
Complex UI, more code, JSP/Spring preferred for large applications.
Example - Basic Servlet
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException {
[Link]().println("Hello from Servlet");
}
}
Example - Servlet Lifecycle
public void init() { [Link]("Init called"); }
public void destroy() { [Link]("Destroy called"); }
Example - [Link] Mapping
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
Example - @WebServlet
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {}
Example - RequestDispatcher
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
Example - sendRedirect
[Link]("[Link]");
Example - HttpSession
HttpSession session = [Link]();
[Link]("user", "Shubham");
Example - Cookie
Cookie c = new Cookie("name", "Shubh");
[Link](c);
Example - Filter
@WebFilter("/secured")
public class AuthFilter implements Filter {
public void doFilter(...) { [Link](req,res); }
}
Example - Listener
@WebListener
public class MyListener implements HttpSessionListener {
public void sessionCreated(...) {}
}
Hibernate Interview Questions & Answers
[Link] is Hibernate?
Hibernate is an ORM (Object Relational Mapping) framework in Java that maps Java objects
to database tables and handles CRUD operations automatically.
[Link] is ORM?
ORM (Object Relational Mapping) is a technique that converts data between object-oriented
programming languages and relational databases.
[Link] of Hibernate?
• Reduces boilerplate JDBC code
• Database-independent (dialects)
• Caching improves performance
• HQL provides object-oriented queries
• Auto table creation
[Link] is a Session in Hibernate?
Session is an interface used to interact with the database. It represents a single unit of work
and provides methods like save(), update(), delete(), get().
[Link] is SessionFactory?
SessionFactory is a heavy-weight, thread-safe object that creates and manages Session
objects.
[Link] between Session and SessionFactory?
Session: Lightweight, not thread-safe, created per request.
SessionFactory: Heavyweight, thread-safe, created once.
[Link] is Hibernate Configuration File?
[Link] contains DB connection details, dialect, mapping resources.
[Link] is Dialect in Hibernate?
Dialect tells Hibernate how to convert HQL/ORM-specific queries to SQL based on database
type.
[Link] are Hibernate Annotations?
Annotations like @Entity, @Id, @Table, @Column map Java classes to DB tables instead of
XML files.
[Link] between get() and load()?
get(): Returns null if not found, loads immediately.
load(): Returns proxy, throws exception if not found.
[Link] is a Persistent Object?
An object associated with a Hibernate Session and represents a database row.
[Link] Hibernate Object States?
• Transient – Object not associated with DB.
• Persistent – Object associated with session.
• Detached – Object once persistent but session closed.
[Link] Hibernate Caching?
Caching improves performance by reducing DB hits. Levels:
1. First Level Cache (Session)
2. Second Level Cache (SessionFactory)
3. Query Cache
[Link] is First Level Cache?
Enabled by default, per-session cache storing objects loaded within the same session.
[Link] is Second Level Cache?
Optional cache shared across sessions. Providers: EhCache, Infinispan.
[Link] is Query Cache?
Cache for HQL/SQL query results. Requires second-level cache.
[Link] between save(), persist(), saveOrUpdate()?
save(): returns ID, inserts immediately.
persist(): does not return ID.
saveOrUpdate(): inserts or updates based on object state.
[Link] is HQL?
Hibernate Query Language – object-oriented query language.
[Link] is Criteria API?
API to build dynamic queries programmatically without writing HQL.
[Link] Cascade Types in Hibernate
ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH – defines how operations propagate to
related entities.
[Link] is Lazy Loading?
Loads associated entities only when accessed, improving performance.
[Link] is Eager Loading?
Loads all related entities immediately.
[Link] between Lazy and Eager Loading?
Lazy: On-demand. Eager: Immediately loads related data.
[Link] is @OneToOne mapping?
Defines one-to-one relationship between two entities.
[Link] is @OneToMany mapping?
Defines one-to-many relationship, usually parent-child.
[Link] is @ManyToOne mapping?
Child refers to a parent record.
[Link] is @ManyToMany mapping?
Defines many-to-many relations using a join table.
[Link] Hibernate Transaction Management
Hibernate supports programmatic and declarative transactions using JTA or JDBC.
[Link] is Dirty Checking?
Hibernate automatically updates modified persistent objects without explicit update() call.
[Link] is n+1 select problem?
Occurs when fetching parent triggers additional queries for each child. Solved using JOIN
FETCH or batching.
[Link] is Entity Lifecycle?
Transient → Persistent → Detached → Removed.
[Link] Hibernate Validator
Provides validation annotations such as @NotNull, @Size, @Email.
[Link] is @GeneratedValue?
Defines primary key generation strategies: AUTO, IDENTITY, SEQUENCE, TABLE.
[Link] between SQL and HQL?
SQL – database-specific.
HQL – object-oriented and DB-independent.
[Link] is JPQL?
Java Persistence Query Language used in JPA, similar to HQL.
[Link] is @Embeddable & @Embedded?
Used to embed value objects inside entities.
Spring Interview Questions & Answers
Spring Core
[Link] is Spring Framework?
Spring is a lightweight, open-source framework for building enterprise Java applications. It
provides IoC, DI, AOP, and modular components.
[Link] is Inversion of Control (IoC)?
IoC is a design principle where the control of object creation is transferred from the
application to the Spring container.
[Link] is Dependency Injection (DI)?
DI injects required dependencies (objects) into a class instead of the class creating them
itself.
[Link] of Dependency Injection?
1. Constructor Injection
2. Setter Injection
3. Field Injection (Not recommended)
[Link] is ApplicationContext?
ApplicationContext is the central interface for Spring. It manages beans, lifecycle, AOP,
events, messages.
[Link] between BeanFactory and ApplicationContext?
BeanFactory: Basic container.
ApplicationContext: Advanced container with AOP, events, i18n, messageSource.
[Link] is a Spring Bean?
Object managed by the Spring IoC container.
[Link] Scopes in Spring?
singleton, prototype, request, session, application, websocket
[Link] is @Component, @Service, @Repository, @Controller?
@Component – generic bean.
@Service – business logic.
@Repository – DAO.
@Controller – MVC controller.
[Link] is Autowiring?
Automatically injecting dependencies using @Autowired.
[Link] is AOP in Spring?
Aspect Oriented Programming used for cross-cutting concerns like logging, security,
transactions.
[Link] are Aspect, Advice, Pointcut, JoinPoint?
Aspect: Modular cross-cutting logic.
Advice: Action taken.
Pointcut: Where advice applies.
JoinPoint: Actual place in code.
[Link] Container Lifecycle?
Instantiation → Dependency Injection → Initialization → Ready → Destruction
Spring MVC
[Link] is Spring MVC?
Spring Web MVC is a framework for building web applications using MVC architecture.
[Link] MVC Architecture?
Model – Data
View – UI
Controller – Request handling
[Link] DispatcherServlet?
Front controller for all web requests. Dispatches requests to controllers.
[Link] the flow of Spring MVC?
Client → DispatcherServlet → HandlerMapping → Controller → ModelAndView →
ViewResolver → Response to client
[Link] is @Controller?
Defines a controller class that handles web requests.
[Link] between @Controller and @RestController?
@Controller returns views.
@RestController returns JSON/XML directly.
[Link] is @RequestMapping?
Maps URLs to controller methods.
[Link] is Model, ModelMap, ModelAndView?
Used to pass data to the view layer.
[Link] is ViewResolver?
Resolves logical view names to actual JSP/HTML templates.
Spring Boot
[Link] is Spring Boot?
Spring Boot simplifies Spring development by providing auto-configuration, embedded
servers, and starter dependencies.
[Link] Boot Features?
Auto-config, starters, embedded Tomcat, Actuator, no XML.
[Link] is Auto-Configuration?
Spring Boot automatically configures beans based on classpath and properties.
[Link] is Starter Dependency?
Pre-configured dependency bundles like spring-boot-starter-web, spring-boot-starter-jpa.
[Link] is [Link] / [Link]?
Central configuration file for the project.
[Link] is @SpringBootApplication?
Combination of @Configuration + @EnableAutoConfiguration + @ComponentScan.
[Link] does Spring Boot run without [Link]?
It uses embedded server (Tomcat/Jetty) and annotations instead of XML.
[Link] is Spring Boot Actuator?
Provides health, metrics, info, monitoring endpoints.
[Link] is Spring Boot CLI?
Command-line tool used to run Groovy-based Spring apps.
[Link] is the difference between Spring and Spring Boot?
Spring: Manual config.
Spring Boot: Auto config + embedded server + starters.
[Link] Spring Boot JPA?
An ORM layer using Hibernate + repository interfaces for CRUD operations.
[Link] is @Entity, @Id, @GeneratedValue?
Used to map Java classes to DB tables.
[Link] are Repository Interfaces?
CrudRepository, JpaRepository → auto CRUD methods.
[Link] Spring Boot Microservices?
Boot is used to build microservices with REST API, Eureka, Feign, Config Server.
[Link] is Spring Boot Security?
Provides authentication and authorization using filters and @EnableWebSecurity.