Spring Boot
@GetMapping
@GetMapping annotation in Spring is a powerful for building RESTful web services. It maps HTTP GET requests to a specific handler method in Spring controllers. With the help of @GetMapping annotation we can easily define endpoints of RESTful API and handle various HTTP requests. @GetMapping annotation is used for mapping HTTP GET requests onto specific handler methods. It is composed annotation that acts as a shortcut for @RequestMapping(method=RequestMethod.GET).
@PostMapping
@PostMapping annotation in Spring MVC framework is a powerful tool for handling the HTTP POST requests in your RESTful web services. It maps specific URLs to handler methods allowing you to receive and process data submitted through POST requests. The @PostMapping annotation is a Spring annotation that is used to map HTTP POST requests onto specific handler methods. It is a shortcut for @RequestMapping(method=RequestMethod.POST).
@SpringBootApplication
@SpringBootApplication: This annotation is used to bootstrap a Spring Boot application. It is a combination of @Configuration, @EnableAutoConfiguration, and @ComponentScan.
Entity
A class which should be persisted in a database it must be annotated with javax.persistence.Entity. Such a class is called Entity. JPA uses a database table for every entity. Persisted instances of the class will be represented as one row in the table. All entity classes must define a primary key, must have a non-arg constructor and or not allowed to be final. Keys can be a single field or a combination of fields. JPA allows to auto-generate the primary key in the database via the @GeneratedValue annotation. By default, the table name corresponds to the class name.
Spring Data JPA
A module within the Spring Data framework that provides an abstraction layer on top of JPA (Java Persistence API). It aims to simplify the development of data access layers by reducing boilerplate code and providing a more intuitive and concise API. Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA-based (Java Persistence API) repositories. It makes it easier to build Spring-powered applications that use data access technologies. Implementing a data access layer for an application can be quite cumbersome. Too much boilerplate code has to be written to execute the simplest queries. Add things like pagination, auditing, and other often-needed options, and you end up lost. Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that's actually needed. As a developer you write your repository interfaces using any number of techniques, and Spring will wire it up for you automatically. You can even use custom finders or query by example and Spring will write the query for you!
Opinionated Approach
An opinionated approach takes the position that there is one way that is significantly easier than all the others. By design, the software limits designers, encouraging them into doing things in that prescribed way. It provides a well-paved path, a best practice that will work for most people in most situations. The app is written sticking closely to these best practices and widespread conventions. An opinionated approach makes collaboration and getting help with a coding project much easier—other developers who have experience with that framework will have immediate familiarity with the new app and can jump right in.
Unopinionated Approach
An unopinionated approach is adopted if all solutions require roughly the same amount of effort or complexity. It takes the position that there's no one right way to arrive at a solution to a problem. Rather, it provides flexible tools that can be used to solve the problem in many ways. Unopinionated frameworks have the benefit of providing lots of flexibility in development and they put more of the control in developers' hands. The main disadvantage with so much flexibility is that the developer has more decisions to make and may end up having to write more code because the framework is so open-ended and well, unopinionated.
@DeleteMapping
Annotation for mapping HTTP DELETE requests onto specific handler methods. Specifically, @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE).
@PutMapping
Annotation for mapping HTTP PUT requests onto specific handler methods. Specifically, @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT).
Annotations
Annotations are a form of metadata that provide additional information about Java code to the compiler and runtime environment. Annotations are used in Spring Boot to configure and customize various aspects of the application. Annotations are denoted by the "@" symbol, followed by the name of the annotation, and may include attributes enclosed in parentheses: - @SpringBootApplication: annotation is used to bootstrap a Spring Boot application. It is a combination of @Configuration, @EnableAutoConfiguration, and @ComponentScan. - @Autowired is used for dependency injection. - @Component: used to mark a class as a Spring Bean. It tells Spring to manage the lifecycle of the bean and to inject its dependencies. - @Service: is typically used to define a business logic layer in a Spring application.
Repository Interface
By extending the JpaRepository interface, Spring Data JPA provides a set of CRUD (create, read, update, delete) methods that can be used without any implementation. To use Spring Data JPA: Add the spring-data-jpa dependency to the maven project Configure the database connection in the application.properties file
Convention over Configuration (Coding by Convention)
Convention over configuration, sometimes called coding by convention, is a concept used in application frameworks to reduce the number of decisions that a developer has to make. It adheres to the "don't repeat yourself" principle to avoid writing redundant code. Coding by convention strives to maintain flexibility while allowing a developer to only write code for the unconventional aspects of the app they're creating. When the desired behavior of the app matches the conventions established, the app will just run by default without having to write configuration files. The developer will only need to explicitly write configuration files if the desired behavior strays from the "convention."
Dependency Injection (DI)
Dependency injection is a pattern we can use to implement IoC, where the control being inverted is setting an object's dependencies. Connecting objects with other objects, or "injecting" objects into other objects, is done by an assembler rather than by the objects themselves.
Persistence Context
Describes the relationship between all the Entity instances in our program and their representations in the underlying database.
JPA Architecture
EntityManagerFactory: This is a factory class for EntityManager instances. It creates and manages EntityManager instances. EntityManager: It is an interface that manages persistence operations on objects. It acts as a factory for Query instances. Entity: Entities are persistence objects that are stored as records in a database. EntityTransaction: It has a one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class. Persistence: This class contains static methods to obtain EntityManagerFactory instances. Query: This interface is implemented by each JPA vendor to obtain relational objects that meet specific criteria.
application.properties
In a spring boot application, the application.properties file is used to write the application-related property into that file. This file contains the different configuration which is required to run the application in a different environment, and each environment will have a different property defined by it. Inside the application properties file, we define every type of property like changing the port, database connectivity, connection to the eureka server, and many more.
CRUD
In computer programming, create, read, update, and delete are the four basic operations of persistent storage. CRUD is also sometimes used to describe user interface conventions that facilitate viewing, searching, and changing information using computer-based forms and reports.
Inversion of Control (IoC)
Inversion of Control is a principle in software engineering which transfers the control of objects or portions of a program to a container or framework. We most often use it in the context of object-oriented programming. In contrast with traditional programming, in which our custom code makes calls to a library, IoC enables a framework to take control of the flow of a program and make calls to our custom code. To enable this, frameworks use abstractions with additional behavior built in. If we want to add our own behavior, we need to extend the classes of the framework or plugin our own classes. The advantages of this architecture are: decoupling the execution of a task from its implementation making it easier to switch between different implementations greater modularity of a program greater ease in testing a program by isolating a component or mocking its dependencies, and allowing components to communicate through contracts We can achieve Inversion of Control through various mechanisms such as: Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI).
@Service
It is typically used to define a business logic layer in a Spring application.
Relationship Mapping
JPA allows to define relationships between classes, e.g. it can be defined that a class is part of another class (containment). Classes can have one to one, one to many, many to one, and many to many relationships with other classes. A relationship can be bidirectional or unidirectional, e.g. in a bidirectional relationship both classes store a reference to each other while in an unidirectional case only one class has a reference to the other class. Within a bidirectional relationship you need to specify the owning side of this relationship in the other class with the attribute "mappedBy", e.g. @ManyToMany(mappedBy="attributeOfTheOwningClass". Relationship annotations: @OneToOne @OneToMany @ManyToOne @ManyToMany
Hibernate
JPA is the Java specification and not the implementation. Hibernate is an implementation of JPA and uses common standards of Java Persistence API. It is the standard API that allows developers to perform database operations smoothly. It is used to map Java data types with database tables and SQL data types. If you're looking for more control over your database interactions, Hibernate is a good choice, while if you want a simpler and more opinionated approach, Spring Data JPA might be a better fit.
Spring Boot
Java Spring Boot is an open-source tool that makes it easier to use Java-based frameworks to create microservices and web apps. For any definition of Spring Boot, the conversation has to start with Java—one of the most popular and widely used development languages and computing platforms for app development. Developers all over the world start their coding journey learning Java. Flexible and user-friendly, Java is a developer favorite for a variety of apps—everything from social media, web, and gaming apps to networking and enterprise applications.
JPARepository
JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting.
Application Framework
Large bodies of prewritten code that developers can use and add to their own code, as their needs dictate. These frameworks lighten the developer's load for almost any need—whether they're developing mobile and web apps or working with desktops and APIs. Frameworks make creating apps quicker, easier, and more secure by providing reusable code and tools to help tie the different elements of a software development project all together.
Microservices
Microservices are an approach to software development architecture. The "micro" in microservices refers to code being delivered in small, manageable pieces, or components, and each "service" or core function, is created and deployed independently from the other services. The independent components work together and communicate through prescribed API documents called contracts. The small scale and relative isolation of these microservices has many benefits. For example, because this type of architecture is distributed and loosely coupled, the whole app doesn't break if one component fails. Other benefits are improved productivity, easier maintenance, better business alignment, and greater fault tolerance. Microservices describes the architectural process of building a distributed application from separately deployable services that perform specific business functions and communicate over web interfaces. DevOps teams enclose individual pieces of functionality in microservices and build larger systems by combining the microservices like building blocks. Building small, self-contained, ready to run applications can bring great flexibility and added resilience to your code. Spring Boot's many purpose-built features make it easy to build and run your microservices in production at scale.
Object-Relational Mapping (ORM)
Object-relational mapping (ORM) connects object-oriented program (OOP) code with a database and simplifies relational database and OOP language interactions.
POJO
POJOs (Plain Old Java Objects) Entities in JPA are nothing but POJOs representing data that can be persisted in the database. An entity represents a table stored in a database. Every instance of an entity represents a row in the table.
Persistence
Persistence simply means to Store Permanently. In Java we work with Objects and try to store Object's values into database (RDBMS mostly). JPA provides implementation for Object Relation Mapping(ORM) ,so that we can directly store Object into Database as a new Tuple. Object, in JPA, are converted to Entity for mapping it to the Table in Database. So Persisting an Entity means Permanently Storing Object(Entity) into Database.
Spring Differences (vs Spring Boot)
Provides a flexible, completely configurable environment using tools and libraries of prebuilt code to create customized, loosely coupled web apps. - Flexibility. - An unopinionated approach. - To remove dependencies from your custom code. - To implement a very unique configuration. - To develop enterprise applications. What's its key feature? Dependency injection Does it have embedded servers? No. In Spring, you'll need to set up the servers explicitly. How is it configured? The Spring framework provides flexibility, but its configuration has to be built manually. Do I need to know how to work with XML? In Spring, knowledge of XML configuration is required. Are there CLI tools for dev/testing apps? The Spring framework alone doesn't provide CLI tools for developing or testing apps.
Spring Boot Differences (vs Spring)
Provides the ability to create, standalone Spring applications that can just run immediately without the need for annotations, XML configuration, or writing lots of additional code. - Ease of use. - An opinionated approach.* - To get quality apps running quickly and reduce development time. - To avoid writing boilerplate code or configuring XML. - To develop REST APIs. What's its key feature? Autoconfiguration Does it have embedded servers? Yes, Spring Boot comes with built-in HTTP servers like Tomcat and Jetty. How is it configured? Spring Boot configures Spring and other third-party frameworks automatically by the default "convention over configuration" principle. Do I need to know how to work with XML? Spring Boot does not require XML configuration. Are there CLI tools for dev/testing apps? As a Spring module, Spring Boot has a CLI tool for developing and testing Spring-based apps.
REST
REST (Representational State Transfer) is an architectural style for building web services that has become increasingly popular in recent years due to its simplicity and scalability. RESTful web services are designed to be resource-oriented, meaning that each resource has a unique identifier (URI) that can be accessed using standard HTTP methods such as GET, POST, PUT, DELETE, and PATCH.
Spring Web - RESTful Web services with Spring Boot
Spring Boot by default provides support for building RESTful APIs with Spring MVC supported by Spring Web starter module. Spring Web MVC, also known as the Spring Web model-view-controller, provides a robust framework for designing and developing web applications, including RESTful web services. To create a RESTful web service using Spring Web starter project, you: - Define a controller with the @Controller annotation (or the @RestController annotation, which includes @Controller and @ResponseBody) to handle HTTP requests and then - Use the @RequestMapping annotation (or its shortcut variants like @GetMapping or @PostMapping, @PutMapping, and @DeleteMapping) to map URLs to methods in the RESTController
Spring Boot Benefits
Spring Boot gives an easier, quicker path to set up, configure, and run apps. It eliminates the heavy lifting of configuration that is required for setting up most Spring-based apps. Developers can jump right in and use Spring Boot without ever having to learn the underlying Spring framework. Benefits: Reduces time in development and increases productivity—Spring Boot makes it much easier to develop Spring-based apps with Java. Its opinionated approach to the Spring framework decreases the time spent on decisions and repetitive tasks and frees up time to focus on creating and testing the apps. Decreases the need to write boilerplate code, annotations, and XML configuration—There's no need for developers to generate code or configure XML or even learn the Spring framework, if they don't want to. Integrates apps in the Spring project family—Spring Boot apps integrate seamlessly with other projects in the Spring framework ecosystem—such as Spring Data, Spring Cloud, Spring Security—as well as with other trusted cloud services such as Microsoft Azure Spring Cloud. Provides dev/test tools—With Spring Boot's command-line interface (CLI) tool and embedded HTTP servers, it makes it very simple to create environments to dev/test Spring-based apps. Offers plugins and tools to make development easier—Spring Boot offers plugins to be able to work with in-memory databases, as well as other popular build automation tools such as Apache Maven.
Spring Boot Features
Spring Boot gives an easier, quicker path to set up, configure, and run apps. It eliminates the heavy lifting of configuration that is required for setting up most Spring-based apps. Developers can jump right in and use Spring Boot without ever having to learn the underlying Spring framework. Features: Standalone applications—Spring Boot helps create apps that aren't tied to a specific platform and that can run locally on a device without an internet connection or other installed services to be functional. Embedded servers—Spring Boot allows you to embed servers such as Tomcat, Jetty, or Undertow directly. Opinionated approach—Spring Boot simplifies build configurations by providing opinionated starter dependencies. Autoconfiguration—Spring Boot automatically configures Spring and other third-party libraries whenever possible. Production-ready features—Spring Boot provides production-ready features such as metrics, health checks, and externalized configuration.
Spring Data JPA Features
Spring Data JPA provides a set of features that make it easier to work with JPA: - Automatic generation of JPA repository implementation at runtime - JPA Repository manages the persistent data in a Spring Boot Application. - JpaRepository is a JPA-specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. It contains API for basic CRUD operations and also API for pagination and sorting. • Integration with other Spring Data modules such as Spring Data REST and Spring Data MongoDB
Spring
Spring is an open-source project that provides a streamlined, modular approach for creating apps with Java. The family of Spring projects began in 2003 as a response to the complexities of early Java development and provides support for developing Java apps. The name, Spring, alone usually refers to the application framework itself or the entire group of projects, or modules. Java Spring Boot is one specific module that is built as an extension of the Spring framework.
Persistence Units
The EntityManager is created by the EntityManagerFactory which is configured by the persistence unit. The persistence unit is described via the persistence.xml file in the META-INF directory of the source folder. A set of entities which are logical connected will be grouped via a persistence unit. The persistence.xml file defines the connection data to the database, e.g. the driver, the user and the password.
JPA (Java/Jakarta Persistence API)
The Java Persistence API deals with the way relational data is mapped to Java objects ("persistent entities"), the way that these objects are stored in a relational database so that they can be accessed at a later time, and the continued existence of an entity's state even after the application that uses it ends. Mapping Java objects to database tables and vice versa is called Object-relational mapping (ORM). The Java Persistence API (JPA) is one possible approach to ORM. Via JPA the developer can map, store, update and retrieve data from relational databases to Java objects and vice versa. JPA can be used in Java-EE and Java-SE applications. JPA is a specification and several implementations are available. Popular implementations are Hibernate, EclipseLink and Apache OpenJPA. The reference implementation of JPA is EclipseLink. JPA permits the developer to work directly with objects rather than with SQL statements. The JPA implementation is typically called persistence provider. The mapping between Java objects and database tables is defined via persistence metadata. The JPA provider will use the persistence metadata information to perform the correct database operations. JPA metadata is typically defined via annotations in the Java class. Alternatively, the metadata can be defined via XML or a combination of both. A XML configuration overwrites the annotations. The following description is based on the usage of annotations. JPA defines a SQL-like Query language for static and dynamic queries. Most JPA persistence providers offer the option to create the database schema automatically based on the metadata.
Entity Manager
The entity manager javax.persistence.EntityManager provides the operations from and to the database, e.g. find objects, persists them, remove objects from the database, etc. In a JavaEE application the entity manager is automatically inserted in the web application. Outside JavaEE you need to manage the entity manager yourself. Entities which are managed by an Entity Manager will automatically propagate these changes to the database (if this happens within a commit statement). If the Entity Manager is closed (via close()) then the managed entities are in a detached state. If synchronize them again with the database a Entity Manager provides the merge() method. The persistence context describes all Entities of one Entity manager.
Persistence of Fields
The fields of the Entity will be saved in the database. JPA can use either your instance variables (fields) or the corresponding getters and setters to access the fields. You are not allowed to mix both methods. If you want to use the setter and getter methods the Java class must follow the Java Bean naming conventions. JPA persists per default all fields of an Entity, if fields should not be saved they must be marked with @Transient. By default each field is mapped to a column with the name of the field.
@RestController
This annotation is used to create a RESTful web service. It is a specialized version of the @Controller annotation that adds support for the HTTP methods GET, POST, PUT, DELETE, and others.
@Entity
This annotation is used to define an entity class. It is typically used to represent a table in a database.
@PathVariable
This annotation is used to extract a variable from the URI of a request. It is typically used with the @RequestMapping annotation.
@RequestBody
This annotation is used to extract the body of a request. It is typically used with the @RequestMapping annotation.
@ExceptionHandler
This annotation is used to handle exceptions thrown by a controller method. It can be used to return a specific HTTP response code or error message.
@ResponseBody
This annotation is used to indicate that the return value of a controller method should be serialized and sent as the response body. It is typically used with the @RequestMapping annotation.
@Autowired
This annotation is used to inject dependencies into a Spring Bean. It can be used to inject dependencies on other beans, properties, and constructors.
@RequestMapping
This annotation is used to map HTTP requests to controller methods. It is used to specify the URI of the request and the HTTP method that the method should handle.
@Repository
This annotation is used to mark a class as a Spring Data repository. It tells Spring to generate a repository implementation for the interface.
@GeneratedValue
This annotation is used to specify how the primary key of an entity is generated. It is typically used with the @Id annotation.
@Column
This annotation is used to specify the mapping between an entity field and a column in a database table. It is typically used with the @Entity annotation.
@Table
This annotation is used to specify the name of the table that an entity is mapped to. It is typically used with the @Entity annotation.
@Id
This annotation is used to specify the primary key of an entity. It is typically used with the @Entity annotation.