Chapter 16 - Spring Boot Flashcards

1
Q

What is spring boot? main purpose

A

Spring Boot is a popular framework in the Java ecosystem designed to simplify the process of building and deploying robust, production-ready applications. Its primary purpose is to streamline the development of stand-alone, production-grade applications that are built on the Spring framework.

Here are some key aspects and purposes of Spring Boot:

Simplified Configuration: Spring Boot reduces the need for extensive configuration by providing sensible defaults and auto-configuration. It allows developers to focus more on writing application logic rather than setting up infrastructure.

Embedded Servers: It includes embedded HTTP servers (like Tomcat, Jetty, or Undertow), which means you can run your application as a standalone JAR file without needing to deploy it in a separate web server container.

Dependency Management: It simplifies dependency management by using starter dependencies, which are pre-configured sets of dependencies for specific functionalities (e.g., database, web, security) that can be easily included in your project.

Monitoring and Actuator: Spring Boot Actuator provides production-ready features for monitoring and managing your application. It includes health checks, metrics, info endpoints, etc., which are helpful for monitoring and managing applications in production.

Spring Ecosystem Integration: It seamlessly integrates with the wider Spring ecosystem, enabling easy adoption of other Spring projects like Spring Data, Spring Security, Spring Cloud, etc.

Rapid Development: With its emphasis on convention over configuration, it accelerates the development process by reducing boilerplate code, allowing developers to quickly create applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the @RequestMapping and @RestController annotation in Spring
Boot used for?

A

@RequestMapping: This annotation is used at the method level to map web requests to specific handler methods in a controller class. It’s quite versatile and allows you to map HTTP requests (GET, POST, PUT, DELETE, etc.) to specific methods. For instance, you can define the URL path and HTTP method that the method will handle.

@RestController: This annotation is a specialized version of @Controller and is typically used in combination with @RequestMapping. It’s a convenience annotation that combines @Controller and @ResponseBody. When you annotate a class with @RestController, it’s indicating that every method in that class returns a domain object instead of a view. The response is automatically serialized into JSON or XML, depending on the content negotiation settings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What do you understand by auto-configuration in Spring Boot and how to
disable the auto-configuration?

A

Auto-configuration in Spring Boot is a powerful feature that aims to reduce the burden of manually configuring your application by providing default configurations based on the dependencies you include in your project’s classpath. It analyzes the environment, classpath, and various other factors to automatically configure beans and settings, making development faster and simpler.

Spring Boot’s auto-configuration works by examining the available beans, properties, and conditions in the environment and then automatically configuring certain components. For instance, if your classpath includes a JDBC library and you haven’t explicitly configured a data source, Spring Boot will configure a default data source using sensible defaults, unless you specify your own.

However, there might be scenarios where you want to disable certain auto-configurations. Here are a few ways to achieve that:

Using @EnableAutoConfiguration with exclusions
You can use @EnableAutoConfiguration annotation in your main class and exclude specific classes or configurations that you want to disable:

java
Copy code
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;

@SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
In this example, ErrorMvcAutoConfiguration is being excluded, meaning Spring Boot won’t automatically configure error handling using this configuration.

Using properties to disable auto-configuration
Spring Boot allows you to use properties in your application.properties or application.yml files to disable specific auto-configurations. For example:

properties
Copy code
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
This property disables the default auto-configuration of the data source.

Programmatically disabling specific auto-configuration classes
You can programmatically disable certain auto-configuration classes by excluding them in your SpringApplication:

java
Copy code
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MyApplication.class);
app.setAdditionalProfiles(“disableDataSource”); // Assuming this profile exists
app.run(args);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Spring Vs Spring boot

A

Spring Spring Boot
Spring Framework is a widely used Java EE framework for building applications. Spring Boot Framework is widely used to develop REST APIs.
It aims to simplify Java EE development that makes developers more productive. It aims to shorten the code length and provide the easiest way to develop Web Applications.
The primary feature of the Spring Framework is dependency injection. The primary feature of Spring Boot is Autoconfiguration. It automatically configures the classes based on the requirement.
It helps to make things simpler by allowing us to develop loosely coupled applications. It helps to create a stand-alone application with less configuration.
The developer writes a lot of code (boilerplate code) to do the minimal task. It reduces boilerplate code.
To test the Spring project, we need to set up the sever explicitly. Spring Boot offers embedded server such as Jetty and Tomcat, etc.
It does not provide support for an in-memory database. It offers several plugins for working with an embedded and in-memory database such as H2.
Developers manually define dependencies for the Spring project in pom.xml. Spring Boot comes with the concept of starter in pom.xml file that internally takes care of downloading the dependencies JARs based on Spring Boot Requirement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does @SpringBootApplication work?

A

Here’s what @SpringBootApplication does:

@Configuration: Indicates that the class contains Spring Bean configurations. It allows the class to define beans using @Bean annotations.

@EnableAutoConfiguration: Enables Spring Boot’s auto-configuration feature. It automatically configures the Spring application based on the dependencies present in the classpath. This reduces the need for manual configurations in many cases.

@ComponentScan: Scans for Spring-managed components (such as controllers, services, repositories) within the package and its sub-packages. It discovers and registers these components as Spring Beans.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is ORM design pattern? How does it work?

A

Object-Relational Mapping or ORM is a technique for converting data between Java
objects and relational database

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Hibernate Framework overview

A

Hibernate is a framework that simplifies the use of relational databases in Java
applications, by presenting relational data as simple Java objects, otherwise known as
POJOs. These objects are accessed in the program using SessionManager.
Hibernate takes care of the mapping from Java classes to database tables, and from
Java data types to SQL data types. In addition, it provides data query and retrieval
facilities. It can significantly reduce development time otherwise spent with manual data
handling in SQL and JDBC. Hibernate’s design goal is to relieve the developer from
95% of common data persistence-related programming tasks by eliminating the need
for manual, hand-crafted data processing using SQL and JDBC. However, unlike many
other persistence solutions, Hibernate does not hide the power of SQL from you and
guarantees that your investment in relational technology and knowledge is as valid as
always.
Hibernate also provides implementation of Java Persistence API (JPA)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Hibernate and ORM

A

Hibernate, as an ORM solution, effectively “sits between” the Java application data
access layer and the Relational Database, as can be seen in the diagram above. The
Java application makes use of the Hibernate APIs to load, store, query, etc. its domain
data.
As a Jakarta Persistence provider, Hibernate implements the Java Persistence API
specifications and the association between Jakarta Persistence interfaces and
Hibernate specific implementations can be visualized in the following diagram.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Hibernate and JPA

A

JPA Hibernate
JPA is described in javax.persistence
package.
Hibernate is described in org.hibernate
package.
It describes the handling of relational
data in Java applications.
Hibernate is an Object-Relational
Mapping (ORM) tool that is used to
save the Java objects in the relational
database system.
It is not an implementation. It is only a
Java specification.
Hibernate is an implementation of JPA.
Hence, the common standard which is
given by JPA is followed by Hibernate.
It is a standard API that permits to
perform database operations.
It is used in mapping Java data types
with SQL data types and database
tables.
As an object-oriented query language, it
uses Java Persistence Query
Language (JPQL) to execute database
operations.
As an object-oriented query language, it
uses Hibernate Query Language
(HQL) to execute database operations.
To interconnect with the entity manager
factory for the persistence unit, it uses
EntityManagerFactory interface. Thus,
it gives an entity manager.
To create Session instances, it uses
SessionFactory interface.
To make, read, and remove actions for
instances of mapped entity classes, it
uses EntityManager interface. This
interface interconnects with the
persistence condition.
To make, read, and remove actions for
instances of mapped entity classes, it
uses Session interface. It acts as a
runtime interface between a Java
application and Hibernate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Hibernate vs JDBC:

A

Main advantages of Hibernate over JDBC are as follows:  Database Portability: Hibernate can be used with multiple types of database
with easy portability. In JDBC, developer has to write database specific native
queries. These native queries can reduce the database portability of the code.

 Connection Pool: Hibernate handles connection pooling very well. JDBC
requires connection pooling to be defined by developer.
 Complexity: Hibernate handles complex query scenarios very well with its
internal API like Criteria. So developer need not gain expertise in writing complex
SQL queries. In JDBC application developer writes most of the queries

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Hibernate important interfaces

A

Configuration interface can be implemented in an application to specify the properties
and mapping documents for creating a SessionFactory in Hibernate. By default, a new
instance of Configuration uses properties mentioned in hibernate.properties file.
Configuration is mainly an initialization time object that loads the properties in helps in
creating SessionFactory with these properties. In short, Configuration interface is used
for configuring Hibernate framework in an application.
Configuration: Configuration interface can be implemented in an application to specify
the properties and mapping documents for creating a SessionFactory in Hibernate.
Hibernate application bootstraps by using this interface.
SessionFactory: In Hibernate, SessionFactory is used to create and manage
Sessions. Generally, there is one SessionFactory created for one database. It is a
thread-safe interface that works well in multithreaded applications.
Session: Session is a lightweight object that is used at runtime between a Java
application and Hibernate. It contains methods to create, read and delete operations for
entity classes. It is a basic class that abstracts the concept of persistence.
Transaction: This is an optional interface. It is a short lived object that is used for
encapsulating the overall work based on unit of work design pattern. A Session can
have multiple Transactions.
Query: This interface encapsulates the behavior of an objectoriented query in
Hibernate. It can accept parameters and execute the queries to fetch results. Same
query can be executed multiple times.
Criteria: This is a simplified API to retrieve objects by creating Criterion objects. It is
very easy to use for creating Search like features

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

SessionFactory Hibernate.

A

A SessionFactory represents an “instance” of Hibernate: it maintains the runtime
metamodel representing persistent entities, their attributes, their associations, and their
mappings to relational database tables, along with configuration that affects the
runtime behavior of Hibernate, and instances of services that Hibernate needs to
perform its duties.
Crucially, this is where a program comes to obtain sessions. Typically, a program has a
single SessionFactory instance, and must obtain a new Session instance from the
factory each time it services a client request.
Depending on how Hibernate is configured, the SessionFactory itself might be
responsible for the lifecycle of pooled JDBC connections and transactions, or it may
simply act as a client for a connection pool or transaction manager provided by a
container environment.
The internal state of a SessionFactory is considered in some sense “immutable”. While
it interacts with stateful services like JDBC connection pools, such state changes are
never visible to its clients. In particular, the runtime metamodel representing the entities
and their O/R mappings is fixed as soon as the SessionFactory is created. Of course,
any SessionFactory is threadsafe

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Session in hibernate

A

Session is the main runtime interface between a Java application and Hibernate.
Represents the notion of a persistence context, a set of managed entity instances
associated with a logical transaction.
The lifecycle of a Session is bounded by the beginning and end of the logical
transaction. (But a long logical transaction might span several database transactions.)
The primary purpose of the Session is to offer create, read, and delete operations for
instances of mapped entity classes. An instance may be in one of three states with
respect to a given session:  transient: never persistent, not associated with any Session,  persistent: associated with a unique Session, or  detached: previously persistent, not associated with any Se

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Hibernate caching. Levels of cache

A

If you have queries that run over and over, with the same parameters, query caching
provides performance gains.
A Hibernate Session is the first level of cache for persistent data in a transaction.
The second level of cache is at JVM or SessionFactory level.
Caching introduces overhead in the area of transactional processing. For example, if
you cache results of a query against an object, Hibernate needs to keep track of
whether any changes have been committed against the object, and invalidate the cache
accordingly. In addition, the benefit from caching query results is limited, and highly
dependent on the usage patterns of your application. For these reasons, Hibernate
disables the query cache by default.
Hibernate offers two caching levels:
First level cache is enabled by default. It includes the persistence context. Once an
entity gets managed, that object is added to the internal cache of the current
persistence context (EntityManager or Session).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Session merge vs call

A

The merge() method is used when we want to change a detached entity into the
persistent state again, and it will automatically update the database. The main aim of
the merge() method is to update the changes in the database made by the persistent
object. The merge() method is provided by the Session interface and is available in
org.hibernate.session package.
merge() - Copy the state of the given object onto the persistent object with the same
identifier. If there is no persistent instance currently associated with the session, it will
be loaded. Return the persistent instance. If the given instance is unsaved, save a copy
of and return it as a newly persistent instance. The given instance does not become
associated with the session. This operation cascades to associated instances if the
association is mapped with cascade=”merge

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Save vs saveOrUpdate vs persist

A

Save method first stores an object in the database. Then it persists the given transient
instance by assigning a generated identifier. Finally, it returns the id of the entity that is
just created.
SaveOrUpdate() method calls either save() or update() method. It selects one of these
methods based on the existence of identifier. If an identifier exists for the entity then
update() method is called. If there is no identifier for the entity then save() method is
called as mentioned earlier

17
Q

Lazy loading in Hibernate

A

Lazy loading means that an entity will be loaded only when you actually access the
entity for the first time

18
Q

HQL overview

A

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL,
but instead of operating on tables and columns, HQL works with persistent objects and
their properties. HQL queries are translated by Hibernate into conventional SQL
queries, which in turn performs action on databas

19
Q

Query cache in Hibernate.

A

Hibernate provides Query Cache to improve the performance of queries that run
multiple times with same parameters. At times Query Caching can reduce the
performance of Transactional processing. By default Query Cache is disabled in
Hibernate. It has to be used based on the benefits gained by it in performance of the
queries in an application.
Caching of query results introduces some overhead in terms of your applications
normal transactional processing. For example, if you cache results of a query
against Person, Hibernate will need to keep track of when those results should be
invalidated because changes have been committed against any Person entity.
That, coupled with the fact that most applications simply gain no benefit from
caching query results, leads Hibernate to disable caching of query results by
default.

20
Q

Different types of cascading

A

Jakarta Persistence allows you to propagate the state transition from a parent entity to a
child. For this purpose, the Jakarta Persistence jakarta.persistence.CascadeType
defines various cascade types:
ALL
cascades all entity state transitions.
PERSIST
cascades the entity persist operation.
MERGE
cascades the entity merge operation.
REMOVE
cascades the entity remove operation.
REFRESH
cascades the entity refresh operation.
DETACH
cascades the entity detach operation.
Additionally, the CascadeType.ALL will propagate any Hibernate-specific operation,
which is defined by the org.hibernate.annotations.CascadeType enum:
SAVE_UPDATE
cascades the entity saveOrUpdate operation.
REPLICATE
cascades the entity replicate operation.
LOCK
cascades the entity lock operation.

21
Q

What is the Detached state of an object in Hibernate?

A

An object is in detached state if it was persistent earlier but its Session is closed now.
Any reference to this object is still valid. We can even update this object. Later on we
can even attach an object in detached state to a new session and make it persistent.
Detached state is very useful in application transactions where a user takes some time
to finish the work.

Detached objects have a representation in the database, but changes to the object will
not be reflected in the database, and vice versa. A detached object can be created by
closing the session that it was associated with, or by evicting it from the session with a
call to the session’s evict() method.
In order to persist changes made to a detached object, the application must reattach it
to a valid Hibernate session. A detached instance can be associated with a new
Hibernate session when your application calls one of the load(), refresh(), merge(),
update(), or save() methods on the new session with a reference to the detached
object. After the call, the detached object would be a persistent object managed by the
new Hibernate session.

22
Q

What are the two locking strategies in Hibernate?

A

There are two popular locking strategies that can be used in Hibernate:
Optimistic: In Optimistic locking we assume that multiple transactions can complete
without affecting each other. So we let the transactions do their work without locking the
resources initially. Just before the commit, we check if any of the resource has changed
by another transaction, then we throw exception and rollback the transaction.
Pessimistic: In Pessimistic locking we assume that concurrent transactions will conflict
while working with same resources. So a transaction has to first obtain lock on the
resources it wants to update. The other transaction can proceed with same resource
only after the lock has been released by previous transaction.

23
Q

@SpringBootApplication vs @EnableAutoConfiguration Annotation?

A

@SpringBootApplication annotation indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration, and @ComponentScan.

24
Q

What is the Spring Boot Actuator and its Features?

A

Spring Boot Actuator provides production-ready features for monitoring and managing Spring Boot applications. It offers a set of built-in endpoints and metrics that allow you to gather valuable insights into the health, performance, and management of your application.

Here are some key features provided by Spring Boot Actuator:
Health Monitoring: The actuator exposes a /health endpoint that provides information about the health status of your application. It can indicate whether your application is up and running, any potential issues, and detailed health checks for different components, such as the database, cache, and message brokers.

Metrics Collection: The actuator collects various metrics about your application’s performance and resource utilization. It exposes endpoints like /metrics and /prometheus to retrieve information about HTTP request counts, memory usage, thread pool statistics, database connection pool usage, and more. These metrics can be integrated with monitoring systems like Prometheus, Graphite, or Micrometer.

Auditing and Tracing: Actuator allows you to track and monitor the activities happening within your application. It provides an /auditevents endpoint to view audit events like login attempts, database changes, or any custom events. Additionally, Actuator integrates with distributed tracing systems like Zipkin or Spring Cloud Sleuth to trace requests as they flow through different components.

Environment Information: The actuator exposes an /info endpoint that displays general information about your application, such as version numbers, build details, and any custom information you want to include. It is useful for providing diagnostic details about your application in runtime environments.

Configuration Management: Actuator provides an /configprops endpoint that lists all the configuration properties used in your application. It helps in understanding the current configuration state and identifying potential issues or inconsistencies.

Remote Management: Actuator allows you to manage and interact with your application remotely. It provides various endpoints, such as /shutdown to gracefully shut down the application, /restart to restart the application, and /actuator to list all available endpoints. These endpoints can be secured using Spring Security for proper access control.