0% found this document useful (0 votes)
18 views

Spring Boot

springboot interview help
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Spring Boot

springboot interview help
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

How does Spring Boot works?

Spring Boot automatically configures your application based on the


dependencies you have added to the project by using annotation. The entry
point of the spring boot application is the class that contains
@SpringBootApplication annotation and the main method.
Spring Boot automatically scans all the components included in the project by
using @ComponentScan annotation.
What does the @SpringBootApplication annotation do internally?
The @SpringBootApplication annotation is equivalent to using
@Configuration, @EnableAutoConfiguration, and @ComponentScan with
their default attributes. Spring Boot enables the developer to use a single
annotation instead of using multiple. But, as we know, Spring provided loosely
coupled features that we can use for each annotation as per our project
needs.
Dependency Injection: YouTube Link
Spring Boot uses Dependency Injection (DI) to inject dependencies into
objects. This means that objects are not responsible for creating their own
dependencies, but instead receive them from the Spring container. This has
several benefits:
 Loose coupling: Objects are not tightly coupled to their dependencies,
making them easier to test and maintain.
 Flexibility: You can easily change the implementation of a
dependency without affecting the rest of your code.
 Improved testability: Objects can be easily mocked or injected with
test doubles for unit testing.
Types of Dependency Injection:
 Constructor injection: Dependencies are injected through the
constructor of an object.
 Setter injection: Dependencies are injected through setter methods of
an object.
 Field injection: Dependencies are injected directly into fields of an
object. (Note: This is not recommended by Spring due to testability
concerns.)
Benefits of using Dependency Injection:
 Improved code organization and maintainability
 Reduced boilerplate code.
 Increased testability
 More flexible and loosely coupled code.

Difference between POJO and Beans in Java.


POJO stands for Plain Old Java Object. It is an ordinary Java object, not
bound by any special restriction other than those forced by the Java
Language Specification and not requiring any classpath. POJOs are used for
increasing the readability and re-usability of a program. POJOs have gained
the most acceptance because they are easy to write and understand. There is
no restriction on access-modifiers of fields. They can be private, default,
protected, or public. It is also not necessary to include any constructor in it.
Beans are special type of Pojos. There are some restrictions on POJO to be a
bean.
 All JavaBeans are POJOs but not all POJOs are JavaBeans.
 Serializable i.e., they should implement Serializable interface. Still,
some POJOs who don’t implement a Serializable interface are called
POJOs because Serializable is a marker interface and therefore not of
many burdens.
 Fields should be private. This is to provide complete control on fields.
 Fields should have getters or setters or both. Visibility of getters and
setters is generally public. Getters and setters provide the complete
restriction on fields.
 A no-arg constructor should be there in a bean.
 Fields are accessed only by constructor or getter setters.

Autowiring in spring
Autowiring is a powerful feature in the Spring framework that automatically
injects dependencies into beans. It simplifies configuration and reduces
boilerplate code, making Spring applications more concise and maintainable.
Autowiring can’t be used to inject primitive and string values. It works with
reference only.
Benefits:
 Reduced boilerplate code – Eliminates the need for manual setter
injection.
 Improved maintainability – Makes code cleaner and easier to
understand.
 Increased flexibility – Allows for automatic dependency injection based
on various criteria.
 Reduced errors – Helps prevent typos and configuration mistakes.
Types of autowiring:
 byName – Injects the bean with the same name as the property to be
autowired.
public class MyClass {
@Autowired
private MyDependency dependency;
}

 byType – Injects the bean with the same type as the property to be
autowired.
public class MyClass {
@Autowired
private MyDependency dependency;
}

 Constructor – Injects the bean through the constructor with matching


parameters.
public class MyClass {
private MyDependency dependency;

public MyClass(@Autowired MyDependency dependency) {


this.dependency = dependency;
}
}

 @Qualifier – Used with other autowiring modes to specify the specific


bean to inject.
public class MyClass {
@Autowired
@Qualifier("specialDependency")
private MyDependency dependency;
}

Spring Framework Annotations


Basically, there are 6 types of annotations available in the whole spring
framework.
 Spring Core Annotations
 Spring Web Annotations
 Spring Boot Annotations
 Spring Scheduling Annotations
 Spring Data Annotations
 Spring Bean Annotations
Spring Core Annotations: Annotations present in
org.springframework.beans.factory and
org.springframework.context.annotation packages are commonly known as
Spring Core annotations. We can divide them into two categories:
 DI-Related Annotations:
 @Autowired – @Autowired annotation is applied to the fields, setter
methods, and constructors. It injects object dependency implicitly. We
use @Autowired to mark the dependency that will be injected by the
Spring container.
 Field Injection
class Student {
@Autowired
Address address;
}
 Constructor injection
class Student {
Address address;

@Autowired
Student(Address address) {
this.address =
address;
}
}

 Setter injection
class Student {
Address address;

@Autowired
void setaddress(Address address)
{
this.address = address;
}
}

 @Qualifier - @Qualifier annotation is used in Spring to inject specific


beans when multiple beans are available for the same type. It helps to
resolve bean ambiguities and inject the desired bean into your
application.
Public class MyService {
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;

@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
}

 @Primary - The @Primary annotation is used in Spring to mark a


specific bean as the preferred choice when multiple beans of the same
type exist. It helps to resolve ambiguity and ensure the desired bean is
injected by default when no other qualifiers are specified.
@Configuration
public class MyConfig {

@Bean
@Primary
public DataSource primaryDataSource() {
// ... configure primary data source
}

@Bean
public DataSource secondaryDataSource() {
// ... configure secondary data source
}
}

 @Bean - The @Bean annotation plays a crucial role in Spring


applications by creating and managing bean instances. It simplifies
bean configuration and provides flexibility for managing dependencies
between beans. Provides an alternative to XML-based bean
configuration.
@Configuration
public class MyConfig {

@Bean
public MyService myService() {
return new MyService();
}

@Bean
public MyRepository myRepository(MyDataSource dataSource) {
return new MyRepository(dataSource);
}

@Bean
public MyDataSource myDataSource() {
// Configure and return MyDataSource instance
}
}

 @Lazy - The @Lazy annotation in Spring is used to control the


initialization of beans. By default, Spring initializes all singleton beans
eagerly at application startup. However, using @Lazy allows you to
postpone the initialization of a bean until it is required. Improve
application startup time by reducing the number of beans initialized at
startup. Conserve memory resources by only initializing beans that are
needed.
@Configuration
public class MyConfig {

@Bean
@Lazy
public MyExpensiveService myExpensiveService() {
// ... configure and return MyExpensiveService instance
}
}

 @Required - While @Required was used in earlier Spring versions, it's


no longer recommended in Spring Boot and modern Spring
applications. @Required is deprecated in Spring 5.1 and later. Spring
strongly encourages constructor injection for required dependencies. If
you must use setter injection for optional properties, consider validation
annotations like @NotNull or @NotEmpty. Avoid using @Required in
spring boot projects. If maintaining older code with @Required,
consider refactoring to constructor injection for better maintainability
and reliability.
 @Value - @Value annotation is used for injecting externalized values
from various sources into beans. It simplifies configuration
management by allowing values to be retrieved from configuration files,
environment variables, system properties, or command line arguments.
Application behaviour can be modified without code change.
@Component
public class MyBean {
@Value("${app.name}")
private String appName;

@Value("${server.port:8080}") // Default value if


property not found
private int serverPort;

// ...
}

 @Scope – In Spring Boot and Spring applications, the @Scope


annotation controls the lifecycle and visibility of beans within the
application context. Common Scopes are:
 Singleton (default) – single instance per application context
shared across all components.
 Prototype – New instance for each request for the bean. Ideal
for stateful beans.
 Request – New instance for each HTTP request. Scoped to the
lifecycle of the web request.
 Session – New instance for each HTTP session. Scoped to the
lifecycle of the user’s session.
 Application – Single instance per ServletContext. Shared across
multiple servlets in the same web application.

@Component
@Scope("prototype") // Create a new instance for each request
public class MyBean {
// ...
}
 Context Configuration Annotations
 @Profile – Provides a powerful way to manage different configurations
and bean definitions for distinct environments. Controls which bean are
registered in the application context based on the active profile(s).
Enables you to create tailored configurations for different
environments. Common uses – environment specific configurations,
disabling bean for certain environments, testing different
configurations.
CONFIGURATION CLASS:

@Configuration
public class AppConfig {

@Bean
@Profile("dev")
public DataSource devDataSource() {
// Create development DataSource
}

@Bean
@Profile("prod")
public DataSource prodDataSource() {
// Create production DataSource
}
}

APPLICATION.PROPERTIES FILE
# Common configuration for all environments

APPLICATION-DEV.PROPERTIES FILE

spring.profiles.active=dev
# Development-specific configuration

APPLICATION-PROD.PROPERTIES FILE

spring.profiles.active=prod
# Production-specific configuration

 @Import
 @ImportResource
 @PropertySource, etc.
Spring Web Annotations: Spring annotations present in the
org.springframework.web.bind.annotation package are commonly known as
Spring Web annotations. Some of the annotations that are available in this
category are:
 @RequestMapping – The @RequestMapping annotation is a
cornerstone for defining how incoming HTTP requests are mapped to
specific controller methods. Specifies the URL patterns and HTTP
method(s) that a controller method should handle. Routes requests to
appropriate controllers based on URL patterns and HTTP methods.
Supports various URL patterns and method restrictions for fine-grained
control.
@RestController
@RequestMapping("/api/users")
public class UserController {

@GetMapping("/{userId}") // Handles GET requests to


/api/users/{userId}
public User getUser(@PathVariable int userId) {
// ...
}

@PostMapping("/create") // Handles POST requests to


/api/users/create
public User createUser(@RequestBody User user) {
// ...
}
}

 @RequestBody – Instructs Spring MVC to bind the request body


content to a specific method argument. Converts the raw request data
(often JSON or XML) into a Java object representing the target
argument type. Typically used for POST, PUT, PATCH requests that
send data in the request body.
@PostMapping("/create")
public User createUser(@RequestBodyUser user) {
// ... process user data
}

 @PathVariable – The @PathVariable annotation plays a crucial role in


extracting dynamic segments from URL paths and binding them to
method arguments. Extracts value from variable paths of URL paths
(defined within curly branches {}). Injects these captured values as
method arguments in controller methods. Enable flexible mapping of
request URLs to controller methods based on varying path segments.
The @PathVariable name should match the variable name in the URL
pattern. Can make path variables optional by setting the required
attribute to false.
@GetMapping("/users/{userId}")
public User getUser(@PathVariable("userId")int userId) {
// Retrieve user with the given userId
}

 @RequestParam – The @RequestParam annotation provides a


mechanism to access query parameters from the request URL and
bind them to method arguments. Facilitates retrieval of user-provided
data or additional information from the request URL. Parameters are
required by default. Set required = false to make them optional.
@GetMapping("/search")
public List<User> searchUsers(@RequestParam("name")String name,
@RequestParam("age")int age) {
// Search users based on name and age
}

 Response Handling Annotations


 @ResponseBody – Signals to Spring MVC that the return value
of a controller method should be directly written into the
response body, rather than rendering a view. Facilitates the
creation of RESTful APIs and services that primarily exchange
data in formats like JSON and XML. Streamlines the process of
returning data without the need for view resolution.
@GetMapping("/users/{userId}")
@ResponseBody
public User getUser(@PathVariable int userId) {
// Retrieve user data
return user; // User object will be serialized as JSON
}

 @ExceptionHandler – The @ExceptionHandler annotation in spring


boot declares specific methods within controllers to handle exceptions
that occur during request processing. Provides a way to manage
exceptions within the controller layer, rather than relying on global
exception resolvers. Enables you to create tailored error responses
based on the exception type and context. The annotated method will
be invoked when an exception of the specified type is thrown within
that controller.
@Controller
public class UserController {

@GetMapping("/users/{userId}")
public User getUser(@PathVariable int userId) {
// ...
if (userNotFound) {
throw new UserNotFoundException();
}
// ...
}

@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorResponse>
handleUserNotFound(UserNotFoundException ex) {
return new ResponseEntity<>(new ErrorResponse("User
not found"), HttpStatus.NOT_FOUND);
}
}

 @ResponseStatus – The @ResponseStatus annotation explicitly


specifies the HTTP status code that should be returned in the
response. Typically used with exception classes to indicate the
appropriate status code when a specific exception is thrown. Can also
be applied to controller methods to directly set the status code for
successful responses.
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "User
not found")

Public class UserNotFoundException extends RuntimeException {


// ...
}

@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/users")
public User createUser(@RequestBody User user) {
// ...
} // Will return 201

 @Controller - Spring @Controller annotation is also a specialization of


@Component annotation. The @Controller annotation indicates that a
particular class serves the role of a controller. Spring Controller
annotation is typically used in combination with another handler
methods based on the @RequestMapping annotation. It can be applied
to classes only. It’s used to mark a class as a web request handler. It’s
mostly used with Spring MVC applications. This annotation acts as a
stereotype for the annotated class, indicating its role. The dispatcher
scans such annotated classes for mapped methods and detects
@RequestMapping annotations.
 @RestController – The @RestController annotation marks a class as a
controller that handles RESTful web service requests, streamlining the
development of REST APIs. Combines @Controller and
@ResponseBody. Acts as a convenient shortcut for combining these
annotations, ensuring the method return values are automatically
written to the response body as JSON and XML. Facilitates the
creation of controllers that primarily focus on returning data, rather than
rendering views. Automatically applies @ResponseBody to all the
methods within the controller, ensuring data-driven responses.
 @ModelAttribute
 @CrossOrigin – Explicitly permits web browsers to make requests to a
server from a different domain than the on that served the webpage,
addressing cross-origin resource sharing restrictions. Bypasses the
browser’s security policy that typically blocks cross-origin requests,
allowing for greater flexibility in web application communication.
@CrossOrigin(origins = "https://www.example.com", methods =
{RequestMethod.GET, RequestMethod.POST})
@RestController
@RequestMapping("/api/users")
public class UserController {
// ...
}

Spring Boot Annotations: Spring annotations present in


org.springframework.boot.autoconfigure and
org.springframework.boot.autoconfigure.condition packages are commonly
known as Spring Boot annotations. Some of the annotations that are available
in this category are:
 @SpringBootApplication – Acts as a single, powerful annotation that
encapsulates several core Spring Boot features, simplifying application
setup and configuration. Automatically activates essential components
for a Spring Boot application like – Spring’s component scanning and
auto-configuration, configuration properties support, websocket,
embedded server, aspect-oriented programming (AOP). Key
Components it encapsulates:
 @SpringBootConfiguration, designates a class as Spring
configuration class, enabling bean definition and configuration.
 @EnableAutoConfiguration, triggers Spring Boot’s auto-
configuration mechanism, which automatically configures beans
based on dependencies and configuration properties.
 @ComponentScan, scans for and registers Spring components
(classes annotated with @Component, @Service, @Repository,
@Controller, etc) within the package of the annotated class and its
sub-packages.
Spring Scheduling Annotations: Spring annotations present in the
org.springframework.scheduling.annotation packages are commonly known
as Spring Scheduling annotations. Some of the annotations that are available
in this category are:
 @EnableAsync – Add this annotation to a Spring configuration class
(e.g., the one with @SpringBootApplication) to activate Spring’s
asynchronous method execution capabilities. Spring uses a
TaskExecutor to manage asynchronous tasks. Spring provides a
default SimpleAsyncTaskExecutor if none is configured.
@SpringBootApplication
@EnableAsync
public class MyApplication {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new
ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
return executor;
}

@Async
public void someLongRunningMethod() {
// Perform long-running task asynchronously
}
}

 @EnableScheduling – Enables the scheduling of tasks for automatic


execution based on specified times or intervals. Leverages Spring’s
built-in task scheduler infrastructure for managing scheduled tasks.
Add this annotation to a Spring configuration class, typically the one
with @SpringBootApplication. Spring manages scheduled tasks using
a TaskScheduler bean, configurable for specific requirements.
@SpringBootApplication
@EnableScheduling
public class MyApplication {

@Scheduled(fixedRate = 5000) // Execute every 5 seconds


public void scheduledTask() {
// Perform scheduled task
}
}

 @Async – Marks methods to be executed in a separate thread,


enabling non-blocking operations and potential performance
enhancements. Allows multiple methods to run concurrently, improving
responsiveness and resource utilization. Add the @Async annotation to
methods you want to execute asynchronously. Ensure @EnableAsync
is enabled in your configuration. Asynchronous methods often run
outside the main thread’s transaction, so handle transactions carefully.
Asynchronous methods can return values, but callers won’t receive
them directly due to separate threads. Use Future or other
mechanisms for delayed results.
@Service
public class MyService {

@Async
public void someLongRunningMethod() {
// Perform long-running task in a separate thread
}
}
 @Scheduled – Marks method as scheduled tasks, ensuring their
automatic execution based on specified scheduling expressions.
Automates tasks for periodic execution, specific time-based events, or
delayed execution, streamlining background processes.
@SpringBootApplication
@EnableScheduling
public class MyApplication {
@Scheduled(fixedRate = 5000) // Execute every 5 seconds
public void scheduledTask() {
// Perform scheduled task
}
@Scheduled(cron = "0 0 12 * * ?") // Execute daily at noon
public void dailyTask() {
// Perform daily task
}
}

Spring Data Annotations: Spring Data provides an abstraction over data


storage technologies. Hence the business logic code can be much more
independent of the underlying persistence implementation. Some of the
annotations that are available in this category are:
 Common Spring Data Annotations
 @Transactional – The @Transactional annotation plays a
crucial role in managing database transactions within Spring
applications. Indicates that a method and its nested calls should
be treated as a single unit of work within a database transaction.
Guarantees that all database operations within the transaction
succeed or fail together, preventing partial updates and data
inconsistencies. Automatically rolls back the transaction if any
exception occurs, ensuring data integrity and avoiding manual
rollback logic. Typically applied to service methods that perform
multiple database operations.
@Service
public class UserService {

@Transactional
public User createUser(User user) {
// Create user record
user = userRepository.save(user);
// Send welcome email
emailService.sendWelcomeEmail(user);
// If any operation fails, the entire transaction
will be rolled back
return user;
}
}

 @Param – In Spring Data, @Param is used within named parameter


queries. Map named variables in your SQL query to specific method
arguments based on their names. Provides more clarity and readability
compared to positional parameters.
// Repository interface
Public interface UserRepository extends JpaRepository<User,
Long> {

@Query("SELECT u FROM User u WHERE u.username =


:username")
User findByUsername(@Param("username")String username);
}

 @Id – Marks a field with an entity class as the primary key, unique
identifying each entity instance in the database. Spring Data relies on
@Id to correctly perform entity persistence, retrieval, and operations.
Spring Data supports various ID generation strategies – Auto-
generation, Manual assignment, or Custom strategies. @Id is used to
define foreign keys in entity relationships, mapping associations
between entities. Employ @EmbeddedId or @IdClass for entities with
composite primary keys.
 @Transient – Marks a field within an entity class to be ignored by
Spring Data’s persistence mechanism. Fields annotated with
@Transient won’t be persisted to or retrieved from the database. Fields
that can be computed from other persisted data, fields used for internal
calculations or temporary data that don’t need permanent storage or
fields, fields containing sensitive information that shouldn’t be stored in
the database, and fields representing data managed externally, not
directly persisted by Spring Data.
@Entity
public class User {
@Id
private Long id;

private String name;

@Transient
private String transientField; // Not persisted
}

 @CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate


 Spring Data JPA Annotations
 @Query
 @Procedure
 @Lock
 @Modifying
 @EnableJpaRepositories
 Spring Data Mongo Annotations
 @Document
 @Field
 @Query
 @EnableMongoRepositories
Spring Bean Annotations: There’re several ways to configure beans in a
Spring container. You can declare them using XML or you can declare beans
using the @Bean annotation in a configuration class or you can mark the
class with one of the annotations from the org.springframework.stereotype
package and leave the rest to component scanning. Some of the annotations
that are available in this category are:
 @ComponentScan – Instructs Spring to scan specific packages for
classes annotated with Spring stereotypes and automatically register
them as beans within the application context. This simplifies wiring
beans together and enabling Spring’s core features like dependency
injection and configuration.
 @Configuration – Identifies a class as a source of bean definitions for
the Spring application context. Allows you to create beans and
configure their dependencies using Java code instead of XML.
Combines various configuration elements into a single class for better
organization and modularity.
 Stereotype Annotations
 @Component – Identifies a class as a candidate for auto-
detection and registration as a bean within the Spring
application context. Serves as the base annotation for more
specific stereotypes like @Service, @Repository, and
@Controller, all of which act as specializations of @Component.
 @Service – Identifies a class as belonging to the business logic
layer of your Spring application. Spring automatically detects
and registers @Service annotated classes as bean in the
application context. Enables dependency injection for
collaboration with other beans in your application.
 @Repository – Identifies a class as responsible for interacting
with a data store (database, file system, etc.), signalling its role
as a data access layer component. Enables Spring to translate
persistence-related exceptions (e.g., SQLException) into
Spring’s DataAccessException hierarchy, promoting a
consistent exception handling approach and hiding technology-
specific details.
 @Controller

Spring Bean Scope


 Singleton
 Prototype
 Request
 Session
 GlobalSession
Spring JDBC
Spring JDBC is a framework that simplifies the process of working with
databases in Java applications. It provides a template class for executing
common database operations, and it also eliminates the need to write
boilerplate code to handle exceptions and manage database connections.
The Spring framework provides a number of advantages for data access,
including the ability to use a consistent API for different types of data access
technologies, the ability to abstract away the details of the underlying data
access technology, and the ability to manage transactions declaratively.
How can you fetch the auto-generated keys from a table after inserting a
new row?
You can use the JdbcTemplate’s update() method to execute an INSERT
statement and return the auto-generated keys. You will need to pass in a
PreparedStatementSetter to set the values for the insert, as well as a
KeyHolder to hold the generated keys.
How do you retrieve data as objects instead of relational results in
Spring JDBC?
In Spring JDBC, you can use the JdbcTemplate class to execute SQL queries
and map the results to Java objects. The JdbcTemplate class provides
several methods for mapping the results of a query to an object, including the
queryForObject() and query() methods.
What is JdbcTemplate?
JdbcTemplate is a utility class that simplifies JDBC code, especially code that
deals with opening and closing connections, executing statements, and
handling resultsets. JdbcTemplate is thread-safe once configured, so multiple
threads can access it concurrently without having to worry about data
corruption or other thread-safety issues.
Is it possible to execute multiple statements simultaneously with Spring
JDBC? If yes, then how?
Yes, it is possible to execute multiple statements simultaneously with Spring
JDBC. This can be accomplished by using the JdbcTemplate.batchUpdate()
method. This method takes an array of SQL statements and an array of
parameters. The SQL statements will be executed in the order they are
provided, and the parameters will be bound to the corresponding SQL
statement.
In which cases would you not want to use ORM tools like Hibernate and
just go with plain old JDBC?
There are a few reasons you might not want to use an ORM tool like
Hibernate. One reason is if you are working with a legacy database that is not
compatible with Hibernate. Another reason is if you are working on a project
where performance is critical, and you need the extra control that JDBC gives
you. Finally, if you are working on a project where the data model is very
simple, then using an ORM tool might be overkill.
Is it possible to execute DDL statements with Spring JDBC?
Yes, it is possible to execute DDL statements with Sprig JDBC. However, it is
generally not recommended to do so, as DDL statements can potentially
cause data loss. If you absolutely must execute a DDL statement, you can
use the JdbcTemplate.execute() method.
What are some common problems that developers run into during bulk
updates using JDBC?
One common problem is forgetting to set the auto-commit mode to false,
which can lead to each update being committed individually and very slowly.
Another is forgetting to close the connection, statement, and/or result set
objects, which can lead to resource leaks. Finally, developers sometimes
forget to properly handle SQLExceptions, which can cause the bulk update to
fail entirely.
What are some best practices for writing efficient JDBC code?
Some best practices for writing efficient JDBC code include:
 Using PreparedStatements rather than Statement objects whenever
possible
 Using connection pooling to minimize the number of times a connection
needs to be opened and closed.
 Batching SQL statements together to reduce the number of round trips
to the database.
 Using appropriate data types when storing data in database.
 Avoiding unnecessary database calls by caching data whenever
possible.
Explain the difference between Object-Relational Mapping (ORM) and
traditional data access methods like JDBC.
Object-Relational Mapping (ORM)
 Abstraction Layer: ORMs provide a higher-level abstraction over
relational databases, allowing you to work with data in terms of objects
and their relationships rather than raw SQL.
 Object-Oriented Mapping: ORMs map database tables to Java
classes (entities) and columns to object fields, bridging the gap
between object-oriented programming and relational database
structures.
 Simplified Data Operations: You can create, read, update, and delete
objects using the object-oriented paradigm, without writing explicit SQL
statements.
 Relationship Management: ORMs handle associations between
entities (e.g., one-to-many, many-to-many) and manage object
references for efficient navigation and querying.
 Query Generation: Most ORMs offer a query language (like JPQL) or
expression-based API to construct queries in a more object-oriented
way, which are then translated into SQL by the ORM.
Traditional Data Access Methods (JDBC)

 Direct SQL Interaction: JDBC requires you to write and execute SQL
statements directly to interact with the database.
 Manual Data Handling: You need to manually manage result sets,
convert data types, and map them to Java objects.
 More Control: JDBC gives you granular control over database
interactions and query optimization, but at the cost of more code and
potential complexity.
Key Differences:
 Abstraction Level: ORMs provide a higher level of abstraction, while
JDBC requires direct SQL interaction.
 Object-Orientation: ORMs align with object-oriented programming
principles, while JDBC is more procedural.
 Productivity: ORMs can streamline development and reduce
boilerplate code, especially for complex data models.
 Performance: ORMs may have some overhead compared to
optimized JDBC, but they can also offer performance benefits through
caching and efficient query generation.
When to Choose:
ORM:
 When working with complex data models and relationships.
 When prioritizing development speed and maintainability.
 When using a well-established ORM with a proven track record.
JDBC:
 When needing maximum control over database interactions and
performance tuning.
 When working with legacy systems or databases with limited ORM
support.
 When having stringent performance requirements that might not be
met by an ORM.

What are the benefits and drawbacks of using Spring ORM?


Benefits:
 Increased Productivity: Spring Data JPA abstracts away tedious SQL
queries and data mapping, streamlining development and reducing
boilerplate code.
 Simplified Data Access: You can use object-oriented concepts like
entities, relationships, and queries to interact with the database,
making it more intuitive and manageable.
 Improved Maintainability: The clear separation of concerns between
data access logic and business logic facilitates cleaner code structure
and easier maintenance.
 Automatic Transaction Management: Spring Data JPA seamlessly
handles transactions, ensuring data consistency and simplifying error
handling.
 Reduced Errors: With automatic type conversion and error handling,
Spring Data JPA helps prevent common database-related errors.
 Integration with Spring Ecosystem: Spring Data JPA tightly integrates
with other Spring features like dependency injection and caching,
simplifying overall application development.
Drawbacks:
 Performance Overhead: Compared to optimized manual SQL queries,
Spring Data JPA might introduce some overhead due to its internal
processing and query generation.
 Potential Code Bloat: Over-reliance on annotations and generated
code can lead to increased code complexity if not managed effectively.
 Limited Flexibility: While offering significant abstraction, Spring Data
JPA may not always provide the fine-grained control over SQL queries
achievable with direct JDBC programming.
 Learning Curve: Understanding best practices and utilizing advanced
features of Spring Data JPA requires time and effort for developers
unfamiliar with ORMs.
 Database Vendor Dependency: Choosing Spring Data JPA ties you to
a specific set of supported databases and their capabilities.

How does Spring Data manage relationships between entities?


Mapping Relationships:
 Annotations: Spring Data JPA utilizes annotations to express
relationships between entities:
 @OneToOne: Represents a one-to-one relationship.
 @OneToMany: Represents a one-to-many relationship.
 @ManyToOne: Represents a many-to-one relationship.
 @ManyToMany: Represents a many-to-many relationship.
 Join Columns and Tables: These annotations often specify join
columns or join tables to establish the relationship in the database.
@Entity
public class Book {
@Id
private Long id;
// ... other fields

@OneToMany(mappedBy = "book")
private List<Page> pages;
}

@Entity
public class Page {
@Id
private Long id;
// ... other fields

@ManyToOne
@JoinColumn(name = "book_id")
private Book book;
}
Navigation and Cascading:
 Navigation: You can navigate between related entities using object
references: Book book = bookRepository.findById(1L); List<Page>
pages = book.getPages();
 Cascading Operations: Spring Data JPA supports cascading
operations (e.g., saving, deleting) across related entities:
@OneToMany(cascade = CascadeType.ALL) private List<Page>
pages;
How do you handle lazy loading and eager loading of relationships in
Spring Data?
Lazy Loading:
 Default Behavior: Relationships are loaded only when accessed using
getter methods or explicitly fetching them through methods like fetch().
 Benefits: Reduces initial load time by fetching related data only when
needed, especially for large datasets.
 Drawbacks: Can cause additional queries and performance overhead
when accessing relationships later.
Eager Loading:
 Fetching Strategies: Override the default behavior using
FetchType.EAGER in relationship annotations like @OneToMany or
@ManyToOne.
 Benefits: Pre-fetches related data alongside the main entity, eliminating
subsequent queries and potentially improving performance for
frequently accessed relationships.
 Drawbacks: Increases initial load time and memory consumption due to
larger data retrieved.

Application.properties file:
All the application configurations are stored in application.properties or
application.yaml file as key-value pair.
Properties can be changes using the file:
 Core properties
 Cache properties
 Mail properties
 JSON properties
 Data properties
 Transaction properties
 Data migration properties
 Integration properties
 Web properties
 Templating properties
 Server properties
 Security properties
 RSocket properties
 Actuator properties
 Devtools properties
 Testing properties
@ControllerAdvice – It is used in Spring to define global controllers’ advice –
components that are applied to the entire application rather than a specific
controller. It’s often used for handling exceptions globally, providing model
attributes to all controllers, and more.

You might also like