0% found this document useful (0 votes)
16 views183 pages

Spring Boot

Uploaded by

abhilash27062001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views183 pages

Spring Boot

Uploaded by

abhilash27062001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 183

Class Notes: https://tinyurl.

com/SPRINGBOOTNOTES
Admin : 7386095600 [Hemanth]

Spring Boot:
1.​Introduction
2.​Spring Boot Features
3.​Key Components in Spring Boot
4.​Approaches to prepare Spring Boot Applications.
5.​Spring Boot Runners
6.​Properties files in Spring Boot.
7.​Yaml File in Spring Boot.
8.​Spring Boot Profiles
9.​Spring Boot Data JDBC
10.​ Spring Boot Data JPA
11.​ Spring Boot Applications with the IN-Memory Databases.
12.​ Spring Boot Applications with NoSQL Databases.
13.​ Spring Boot Email.
14.​ Spring Boot Batch Processing
15.​ Spring Boot Messaging
a.​ActiveMQ
b.​RabbitMQ
c.​KAFKA
16.​ Spring Boot Web
17.​ Spring Boot Logging
18.​ Spring Boot Rest
19.​ Spring Boot Security[Basic, Oauth2.x]

Prerequisite: Core Java, Basics of JDBC, Servlets, JSPs, Basics


of Hibernate, Spring.

Few Days of time: 8:30PM to 9:30PM


After few days of time, I will take the session from 7:00PM to
8:00PM

Introduction:
1.​Spring Boot is an open Source and Java Based Framework
Developed by Pivotal Team.
2.​Spring boot Makes it easy to create Standalone,
Production-Grade spring applications that we can “just run”.
3.​It simplifies the bootstrapping and development of the
Spring applications.
4.​Spring Boot was designed on the top of existing Spring
Framework to simplify and speedup the spring application
development.
5.​Spring boot can be used to prepare the Spring applications
either by using JAVA or by using Groovy.
6.​Spring Boot simplifies spring application development by
having all the configurations as defaults and the developers
will focus more on the Business logic instead of focussing
on the configurations.
7.​Spring Boot reduces the application development time.
8.​Spring Boot improves the applications productivity.
9.​Spring Boot provides very simple approaches to integrate
Spring boot applications with the Spring echo system like
Spring JDBC, Spring ORM, Spring AOP,....
10.​ Spring Boot follows the “Opinionated Defaults
Configuration” approach to reduce developers' efforts .
Spring boot avoids writing lots of boilerplate code ,
Annotations and XML configurations.
11.​ Spring boot provides Embedded Http Servers like Tomcat,
Jetty, Undertow,.... To develop and test web applications.
12.​ Spring Boot provides CLI[Command Line Interface] tool to
develop and test spring boot Applications from the Command
prompt very easily and quickly.
13.​ Spring Boot has a number of plugins to develop and test
theSpring Boot applications using the build tools like MAVEN
and GRADLE.
14.​ Spring Boot has embedded In memory Databases like H2
Database.
15.​ Spring Boot = ​ Spring Application +
Embedded Servers +
​ ​ ​ Embedded databases +
​ ​ ​ No XML configurations +
​ ​ ​ Less Annotations.

Spring Boot Features:


—---------------------
1. SpringApplication:
SpringApplication is a class provided by the Spring Boot,, it
provides a convenient way to bootstrap the Spring application
that is started from a main() method, SpringApplication has a
static run() to bootstrap and start spring application.

EX:
public class MyApp{
​ public static void main(String[] args){
​ ​ SpringApplication.run(MyApp.class, args);
​ }
}

2. Externalized Configurations:
—-------------------------------
Spring Boot is giving an option to use like to externalize our
application configurations so we can work with the same
application code in different environments. To provide
Externalized configurations we will use properties files, YAML
files, environment variables, command line arguments,...

3. Profiles:
—-----------
In general, in the enterprise applications, we will provide
separate configurations for the project development phase,
Testing phase and Production phase, to manage all those
configurations depending on the project lifecycle phase we will
use profiles, here Profile represents a particular environment
like Development, Testing, Production,... Spring Boot is
providing very good support for profiles in the enterprise
applications by providing @profile() annotation.

4. Logging:
—----------
Spring Boot uses common Logging mechanisms for all internal
logging, Spring Boot Supports the logging mechanisms like Log4j
or Slf4j,.... internally.
5.Internationalization:
—-----------------------
SpringBoot is providing a very good support for the
internalization as per the users local conventions by providing
different properties files or different yaml files.

6. JSON:
—-------
IN enterprise applications we will use JSON as an alternative for
representing and transferring data.

Spring Boot supports the following three types of JSON


implementations.

1.​Gson
2.​Jackson
3.​JSON-B
Spring Boot uses Jacson as the predefined and default
implementation internally.

7. Developing Web Applications:


—-------------------------------
Spring boot is well suited for Web application Development and
Spring Boot has the embedded servers like Tomcat, Jetty,... to
deploy and execute the web application.

8. Supporting SQL and NoSQL Databases:


—--------------------------------------
Spring Boot Provides a very good environment to work with the SQL
databases like Oracle, MySQL,.., No SQL Databases like MangoDB
and the In-Memory databases like H2 database,...

9. Messaging:
—-------------
IN general, in enterprise applications, we need a Messaging
system to deliver the messages from the message source to the
message destination.
Spring Boot supports the Messaging Systems like ActiveMQ,
RabbitMQ, KAFKA,....

10. Rest Services:


—------------------
Spring Boot provides a separate module in the form of Spring Boot
REST to integrate Restful services in the Spring Boot
applications.

11. Validations:
—----------------
Spring Boot is providing very good support for the Data
Validations by having Hibernate Bean Validations.
12. Email Support:
—------------------
Spring Boot is providing very good support for Mailing Services
in order to send mails from the SPring application to the Users.

Key Components of Spring Boot:


—------------------------------
Spring Boot has mainly the following four components.

1.​Spring Boot Starters.


2.​Spring Boot AutoConfigurator.
3.​Spring Boot CLI
4.​Spring Boot Actuators

Spring Boot Starters:


—---------------------
The main intention of the Spring Boot starters is to combine a
group of common or related dependencies into a single dependency.

If we want to prepare a Spring WEBMVC application with the CRUD


operation then we have to provide the following jar files.

Spring beans [spring-beans-xxx.jar]


Spring Core [spring-core-xxx.jar]
Spring context [spring-context-xxx.jar]
Spring web [spring-web-xxx.jar]
Spring web mvc [spring-webmvc-xxx.jar]
Spring orm [spring-orm-xxx.jar]
Spring jdbc [spring-jdbc-xxx.jar]
Spring Transaction [spring-tramsaction-xxx.jar]
Servlet api [servlet-xxx.jar]
—--
—---

The above approach will increase the number of dependencies in


the applications, it will increase the configurations in the
build file, it is very difficult to manage all these
dependencies.

To overcome the above problems, Spring Boot has provided an


alternative in the form of Spring Boot Starters.

In the above context, Spring Boot starters will combine all the
related jars into a single jar, so that we can add only one
dependency in the build files.

In Spring Boot, if we want to prepare Spring WEB MVC application


then we have to use the following starter dependency in pom.xml.

“Spring-boot-starter-web”

If we provide the above dependency in the pom.xml file then we


are able to get the following jars.

1.​spring-boot-starter
a.​spring-boot
b.​spring-boot-autoconfigure
c.​spring-boot-starter-logging
2.​Spring-web
3.​Spring-webmvc
4.​spring-boot-starter-tomcat
a.​tomcat-embedded-core
b.​tomcat-embedded-logging-juli
​ —----
​ —----
Spring Boot AutoConfigurator:
—-----------------------------
In general, in the Spring web MVC applications, we have to
provide so many element configurations in the spring
configuration file.

EX:​
1.​Bean Configurations and their dependencies.
2.​Handler Mapping Configurations
3.​View Resolver Configurations
—----
—----
The above approach will increase the number of configurations in
the configuration file, so it is very difficult to manage all
those configurations.

To overcome the above problems, Spring Boot has provided a


solution in the form of Spring Boot AutoConfigurator, here the
Spring Boot AutoConfigurator is able to provide all the common
and default configurations automatically or internally in the
applications, where developers are not required to provide all
those configurations explicitly.

To provide auto configurations in the spring boot applications we


have to use “@SpringBootApplication” annotation over class.

Where the @SpringBootApplication annotation is the combination of


the following annotations.

1.​@Configuration
2.​@ComponentScan
3.​@EnableAutoConfiguration

Spring Boot CLI:


—----------------
Spring Boot CLI[Command Line Interface] is a spring boot
software, it will provide a very good environment to run and test
the spring boot applications from COmmand prompt.

When we run a spring boot application by using Spring Boot CLI


then it will use Spring Boot starters, AutoConfigurator to
resolve all the dependencies and to execute the spring boot
application.

To execute the Spring boot application , Spring Boot CLI has


provided a command in the form of “spring”, where the “spring”
command will execute the spring boot application available in the
form of groovy script that is the .groovy file.

spring run HelloWorld.groovy

Spring Boot Actuators:


—---------------------
Spring Boot Actuators are providing the number of
Production-Ready features like

1.​Spring Boot actuators are providing an environment to manage


and monitor our application by using Http endpoints.
2.​Spring Boot actuators are providing Auditing, health and
metrics automatically in our application.

In the spring boot applications, to get the actuators we will use


the following dependency in the pom.xml file.

spring-boot-starter-actuator

Steps to prepare Spring Boot Application:


—-----------------------------------------
1.​Using Simple MAVEN Project in Eclipse IDE.
2.​Using STS
3.​Using Spring Boot Initializer
4.​Using Spring Boot CLI
Spring Boot Runners:
—--------------------
The main purpose of the Spring Boot Runners is to execute a block
of code automatically immediately after loading the Spring Boot
application.

In the Spring Boot application, Spring Boot Runners will be


executed only one time.

In general, in Spring Boot applications, to override the


configurations data which we provided in the properties file or
yaml file and the default configurations which we have in the
spring boot internally we will use Spring Boot Runners.

In Spring Boot applications, we will use Spring boot Runners to


hold and manage the command line arguments.

Spring Boot has provided the following two types of Runners.

1.​CommandLineRunner
2.​ApplicationRunner

CommandLineRunner:
It is an interface provided by the Spring boot 1.0 version, it is
able to take all the types of command line arguments in the form
of String values in a String[]
There are two types of Command Line Arguments.
1.​Option Arguments:
These command line arguments contain key-value pairs.
EX:​ —-server.port=1234
​ —-application.name=SpringBootApplication

2.​Non Option Arguments:


These Command Line Arguments contain single values.
EX:​ start, stop, add, search,...

CommandLineRunner is not providing any difference between the


option arguments and Non Option arguments.
CommandLineRunner is a functional interface, it has the following
method.

​ public void run(String[] args)

If we want to use CommandLineRunner in Spring boot applications


we will use the following steps.

1.​Prepare an User defined class.


2.​Provide @Component annotation over the user defined class.
3.​Implement CommandLineRunner interface in the user defined
class.
4.​Implement run() method with the logic which we want to
execute.

EX:
App04Application.java
package com.durgasoft.app04;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App04Application {

public static void main(String[] args) {


SpringApplication.run(App04Application.class, args);
System.out.println("Welcome To Spring boot main
class.....");
}

WelcomeRunner.java
package com.durgasoft.app04.runners;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class WelcomeRunner implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println("Welcome To CommandLineRunner
class.....");
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.durgasoft</groupId>
<artifactId>app04</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app04</name>
<description>app04</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

When we execute the Spring Boot application, Spring Boot


Application will perform the following actions.

1.​Spring boot project will be loaded.


2.​Spring Boot Framework will execute the main() method of the
Spring Boot main class.
3.​As part of the main() method, SpringApplication.run() method
will be executed.
4.​The SpringApplication.run() method will perform the complete
booting of the application and at the end of the booting it
will recognize and execute the runner class.

EX:
package com.durgasoft.app05.runners;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class WelcomeRunner implements CommandLineRunner {
public void run(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
}

APp05Application.java
package com.durgasoft.app05;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App05Application {

public static void main(String[] args) {


SpringApplication.run(App05Application.class, args);
}
}
In a single Spring Boot application, we can provide more than one
Command Line Runner, all these command line runners are executed
without following any particular order. If we execute the same
application multiple times then the order of the Runners
execution will be varied from one to another time.

EX:
WelcomeRunner.java
package com.durgasoft.app05.runners;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class WelcomeRunner implements CommandLineRunner {
public void run(String... args) {
System.out.println("WelcomeRunner....");
}
}

HelloRunner.java
package com.durgasoft.app05.runners;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class HelloRunner implements CommandLineRunner {
public void run(String... args) {
System.out.println("HelloRunner....");
}
}

WishRunner.java
package com.durgasoft.app05.runners;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class WishRunner implements CommandLineRunner {
public void run(String... args) {
System.out.println("WishRunner....");
}
}

App05Application.java
package com.durgasoft.app05;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App05Application {

public static void main(String[] args) {


SpringApplication.run(App05Application.class, args);
}
}
In the spring boot applications, if we want to execute all the
command line runners in a particular order we have to use @Order
annotation.

@Order : No particular Order


@Order(value): Particular Order.

If the order value is less then the respective Runner class will
get more priority and it will be executed first.

If the order value is more then the respective Runner class will
get less priority and it will be executed last.

EX:
WishRunner.java
package com.durgasoft.app05.runners;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class WishRunner implements CommandLineRunner {
public void run(String... args) {
System.out.println("WishRunner....");
}
}

HelloRunner.java
package com.durgasoft.app05.runners;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class HelloRunner implements CommandLineRunner {
public void run(String... args) {
System.out.println("HelloRunner....");
}
}

WelcomeRunner.java
package com.durgasoft.app05.runners;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(3)
public class WelcomeRunner implements CommandLineRunner {
public void run(String... args) {
System.out.println("WelcomeRunner....");
}
}

App05Application.java
package com.durgasoft.app05;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App05Application {

public static void main(String[] args) {


SpringApplication.run(App05Application.class, args);
}
}

OP:
WishRunner....
HelloRunner....
WelcomeRunner....

Note: If we provide the same order value to more than one Runner
then all the Runner classes are executed without any particular
order.

ApplicationRunner:
—-----------------
It is a Runner in Spring boot, it is able to take all the types
of command line arguments like option arguments and non option
arguments, but it will manage the option arguments and non option
arguments separately.

ApplicationRunner is a functional interface and it has the


following method.

public void run(ApplicationARguments args)

Where the ApplicationArguments is able to manage the option


arguments and Non Option arguments separately.

To get all the option arguments names we will use the following
method.

​ public Set getOptionNames()

To get all values of a particular Option Argument we will use the


following method.

​ public List getOptionValues(String name)

To check whether the argument name is available or not in the


Option arguments we will use the following method.

​ public boolean containsOption(String name)

To get all the Non option arguments we will use the following
method.
public List getNonOptionArguments()

EX:
TestRunner.java
package com.durgasoft.app06.runner;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class TestRunner implements ApplicationRunner {
public void run(ApplicationArguments args) throws Exception {
System.out.println("Option Arguments Names : " +
args.getOptionNames());
System.out.println("Application Name :
"+args.getOptionValues("application.name"));
System.out.println("server.port Existed? :
"+args.containsOption("server.port"));
System.out.println("Non Option Argument Values : " +
args.getNonOptionArgs());

}
}

App06Application.java
package com.durgasoft.app06;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App06Application {

public static void main(String[] args) {


SpringApplication.run(App06Application.class, args);
}
}

If we run the above application with the command line arguments


--application.name=app06 --server.port=1234 start stop pause edit
Then we are able to get the following outputs.

Option Arguments Names : [server.port, application.name]


Application Name : [app06]
server.port Existed? : true
Non Option Argument Values : [start, stop, pause, edit]

In a Single Spring boot application, it is possible to provide


more than one application runner, here all the application
runners are executed immediately after loading the spring boot
application, by default all the Application Runners are not
executed in a particular order, they may be executed without any
order, but if we want to execute all the Application Runners in a
particular order then we have to use @Order(PriorityValue) at the
Runner classes.

EX:
HelloRunner.java
package com.durgasoft.app07.runners;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(3)
public class HelloRunner implements ApplicationRunner {
public void run(ApplicationArguments args) throws Exception {
System.out.println("HelloRunner.....");
}
}

WishRunner.java
package com.durgasoft.app07.runners;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class WishRunner implements ApplicationRunner {

@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("WishRunner.....");
}
}

WelcomeRunner.java
package com.durgasoft.app07.runners;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class WelcomeRunner implements ApplicationRunner {

@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("WelcomeRunner.....");
}
}

App07Application.java
package com.durgasoft.app07;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App07Application {

public static void main(String[] args) {


SpringApplication.run(App07Application.class, args);
}

WishRunner.....
WelcomeRunner.....
HelloRunner.....

In a Single Spring boot application, it is possible to provide


both Application Runner and Command Line Runner, they will be
executed in a random order, but if we want to execute them in a
particular order then we have to use @Order(priorityValue)
annotation over the Runner class.

EX:
WelcomeRunner.java
package com.durgasoft.app07.runners;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class WelcomeRunner implements ApplicationRunner {

@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner:
WelcomeRunner.....");
}
}

HelloRunner.java
package com.durgasoft.app07.runners;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class HelloRunner implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner: HelloRunner");
}
}

WishRunner.java
package com.durgasoft.app07.runners;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(3)
public class WishRunner implements ApplicationRunner {

@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner: WishRunner.....");
}
}
App07Application.java
package com.durgasoft.app07;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App07Application {

public static void main(String[] args) {


SpringApplication.run(App07Application.class, args);
}

Q)What are the differences between CommandLineRunner and


ApplicationRunner?
—--------------------------------------------------------
1. ​ CommandLineRunner was introduced in Spring Boot 1.0 version.
​ ApplicationRunner was introduced in Spring Boot 1.3 version.

2. ​ CommandLineRunner is a functional interface and it has the


following method.
public void run(String[] args)

ApplicationRunner is a functional Interface and it has the


following method.
public void run(ApplicationArguments args)

3. ​ CommandLineRunner is able to manage all the option arguments


and Non-Option Arguments in the form of a String[] without
providing any differentiation.
ApplihcationRunner is able to manage all the option
arguments and non-option arguments separately.

Properties Files in Spring Boot:


—--------------------------------
properties file is like a text file, it is able to manage the
data in the form of Key-Value pairs.

In general, in java applications we will use the properties files


for the following requirements.

1.​To manage the frequently modified data in Java applications


in order to avoid the recompilation every time.
2.​To manage the labels of the GUI components in the GUI
applications.
3.​To manage local respective messages w.r.t the number of
Locale in Internationalization.
4.​To manage the Exception messages in Exception Handling.
5.​To manage the validation messages in the data Validations.
6.​To manage all the JDBC parameters in the Jdbc applications.
7.​To provide all the database configurations in the Database
related applications like Hibernate Applications.
8.​To manage all the Server configurations in the server side
applications.
—------
—------

In Spring Boot applications, the main purpose of the properties


file is
1.​To manage the application’s logical name.
2.​To manage the server configurations like port numbers,...
3.​To provide the database configurations like datasource name,
driver class name, driver url, database Username, Database
password,...
4.​To Provide the Security configurations like user roles,
access privileges,...
5.​To provide administrative configurations like health checks,
metrics,...
6.​To provide profile configurations like DEV configurations,
QA configurations, PROD configurations,....
—----
—----
In Spring Boot applications we will provide the properties files
under the resources folder.

In Spring Boot applications, the default properties file name is


“application.properties”.

In Spring Boot, tomcat server is an embedded server, the default


port number for the tomcat server is 8080, here if we want to
change the embedded tomcat servers port number we will use the
following property in the properties file.

server.port=1234

In Spring Boot applications, to provide the application’s logical


name we will use the following property in the properties file.

application.name=app01

EX:
application.properties
server.port=1234
spring.application.name=DemoApp

App08Application.java
package com.durgasoft.app08;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App08Application {

public static void main(String[] args) {


SpringApplication.run(App08Application.class, args);
}

Changing the Spring Boot Banner:


In Spring boot applications, we are able to get “Spring” as the
default banner on the console, here it is possible to disable the
spring boot banner in the spring applications by using the
following property in the properties file.

spring.main.banner-mode=off

EX:
application.properties
server.port=1234
spring.application.name=DemoApp
spring.main.banner-mode=off

App08Application.java
package com.durgasoft.app08;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App08Application {

public static void main(String[] args) {


SpringApplication.run(App08Application.class, args);
}

In the Spring Boot applications, it is possible to provide our


own banner in place of the default banner with the following
steps.
1.​Create a Spring Boot project.
2.​Create banner.txt file under the resources.
3.​Generate a custom banner by using any online tool.
[Search for Spring Boot Banner Generator in Google]
https://devops.datenkollektiv.de/banner.txt/index.html
Provide a custom banner with the required settings.
4.​Copy the custom banner to the banner.txt
5.​Provide the banner properties in the application.properties.
application.title, application.version, spring-boot.version

EX:
application.properties
server.port=1234
spring.application.name=DemoApp

application.title=Spring Boot Demo Project


application.version=V1.0
spring-boot.version=3.5.3

banner.txt
,------. ,--. ,--.,------. ,----. ,---. ,---. ,-----.
,------.,--------.
| .-. \ | | | || .--. '' .-./ / O \ ' .-' ' .-. '|
.---''--. .--'
| | \ :| | | || '--'.'| | .---.| .-. |`. `-. | | | ||
`--, | |
| '--' /' '-' '| |\ \ ' '--' || | | |.-' |' '-' '|
|` | |
`-------' `-----' `--' '--' `------' `--' `--'`-----' `-----'
`--' `--'
${application.title} ${application.version}
Powered by Spring Boot ${spring-boot.version}

App08Application.java
package com.durgasoft.app08;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App08Application {

public static void main(String[] args) {


SpringApplication.run(App08Application.class, args);
}

In the Spring Boot applications, it is possible to change the


name and location of the banner file, but we must specify the
name and location of the banner file with the following property.

spring.banner.location=classpath:fileName.txt

IN the spring boot applications, we are able to define our own


properties in the properties file and we are able to access those
properties data in the spring boot applications.

To access a particular property value from the properties file we


have to use the following annotation.

@Value(“${propertyName}”)

EX:
application.properties
spring.application.name=app09

employee.eno=111
employee.ename=Durga
employee.esal=50000
employee.eaddr=Hyd

Employee.java
package com.durgasoft.app09.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Employee {
@Value("${employee.eno}")
private int eno;
@Value("${employee.ename}")
private String ename;
@Value("${employee.esal}")
private float esal;
@Value("${employee.eaddr}")
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

EmployeeRunner.java
package com.durgasoft.app09.runner;

import com.durgasoft.app09.beans.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class EmployeeRunner implements ApplicationRunner {
@Autowired
private Employee employee;
public void run(ApplicationArguments args) throws Exception {
System.out.println("Employee Details");
System.out.println("-------------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
}
}

App09Application.java
package com.durgasoft.app09;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App09Application {

public static void main(String[] args) {


SpringApplication.run(App09Application.class, args);
}

Employee Details
-------------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000.0
Employee Address : Hyd

In the Spring boot application, if the properties file provided


properties names and the bean class properties names are matched
then we are able to copy the data from the properties file to the
bean object directly without using @Value annotation at each and
every property but we have to configure the prefix name of the
properties by using @ConfigurationProperties annotation.

EX:
application.properties
spring.application.name=app10

employee.eno=111
employee.ename=Durga
employee.esal=50000
employee.eaddr=Hyd

Employee.java
package com.durgasoft.app10.beans;

import org.springframework.beans.factory.annotation.Value;
import
org.springframework.boot.context.properties.ConfigurationProperti
es;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "employee")
@Component
public class Employee {

//@Value("${employee.eno}")
private int eno;
//@Value("${employee.ename}")
private String ename;
//@Value("${employee.esal}")
private float esal;
//@Value("${employee.eaddr}")
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

EmployeeRunner.java
package com.durgasoft.app10.runner;

import com.durgasoft.app10.beans.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class EmployeeRunner implements ApplicationRunner {
@Autowired
private Employee employee;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
}
}
App10Application.java
package com.durgasoft.app10;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App10Application {

public static void main(String[] args) {


SpringApplication.run(App10Application.class, args);
}

In Spring Boot applications, if we provide data in the properties


file then the provided data will be stored in an object
internally called Environment object, here we are able to get the
data from the Environment object by using the following method.

public String getProperty(String propName)

EX:
application.properties
spring.application.name=app10

employee.eno=111
employee.ename=Durga
employee.esal=50000
employee.eaddr=Hyd
EmployeeRunner.java
package com.durgasoft.app10.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class EmployeeRunner implements ApplicationRunner {
@Autowired
private Environment environment;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number :
"+environment.getProperty("employee.eno"));
System.out.println("Employee Name :
"+environment.getProperty("employee.ename"));
System.out.println("Employee Salary :
"+environment.getProperty("employee.esal"));
System.out.println("Employee Address :
"+environment.getProperty("employee.eaddr"));
}
}

App10Application.java
package com.durgasoft.app10;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App10Application {

public static void main(String[] args) {


SpringApplication.run(App10Application.class, args);
}

Q)Is it possible to provide more than one properties file in a


single Spring Boot application?
—----------------------------------------------------------------
Ans:
Yes, it is possible to provide more than one properties file in a
single spring boot application, but the names of the properties
files must be different. IN this context, to get the data from
the properties file we have to configure those properties files
with the @PropertySource annotation or @PropertySources
annotation.

EX:
application.properties
spring.application.name=app10

employee.properties
employee.eno=111
employee.ename=Durga
employee.esal=50000
employee.eaddr=Hyd

student.properties
student.sid=S-111
student.sname=Anil
student.saddr=Chennai

customer.properties
customer.cid=C-111
customer.cname=Ramana
customer.caddr=Pune

AppRunner.java
package com.durgasoft.app10.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@PropertySources({
@PropertySource("classpath:employee.properties"),
@PropertySource("classpath:student.properties"),
@PropertySource("classpath:customer.properties")
})
public class AppRunner implements ApplicationRunner {
@Autowired
private Environment environment;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Employee Details");
System.out.println("---------------------");
System.out.println("Employee Number : " +
environment.getProperty("employee.eno"));
System.out.println("Employee Name : " +
environment.getProperty("employee.ename"));
System.out.println("Employee Salary : " +
environment.getProperty("employee.esal"));
System.out.println("Employee Address : " +
environment.getProperty("employee.eaddr"));
System.out.println();

System.out.println("Student Details");
System.out.println("----------------------");
System.out.println("Student Id : " +
environment.getProperty("student.sid"));
System.out.println("Student Name : " +
environment.getProperty("student.sname"));
System.out.println("Student Address : " +
environment.getProperty("student.saddr"));
System.out.println();

System.out.println("Customer Details");
System.out.println("-----------------------");
System.out.println("Customer Id : " +
environment.getProperty("customer.cid"));
System.out.println("Customer Name : " +
environment.getProperty("customer.cname"));
System.out.println("Customer Address : " +
environment.getProperty("customer.caddr"));

}
}

App10Application.java
package com.durgasoft.app10;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App10Application {

public static void main(String[] args) {


SpringApplication.run(App10Application.class, args);
}

Employee Details
---------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000
Employee Address : Hyd

Student Details
----------------------
Student Id : S-111
Student Name : Anil
Student Address : Chennai

Customer Details
-----------------------
Customer Id : C-111
Customer Name : Ramana
Customer Address : Pune

In the properties files, we are able to define place holders like


${name} as the value for the properties and we will provide
values to the place holders in order to provide reusability.

EX:
application.properties
spring.application.name=app10

name=Durga
addr=Hyd

employee.eno=111
employee.ename=${name}
employee.esal=50000
employee.eaddr=${addr}

student.sid=S-111
student.sname=${name}
student.saddr=${addr}

customer.cid=C-111
customer.cname=${name}
customer.caddr=${addr}

AppRunner.java
package com.durgasoft.app10.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component

public class AppRunner implements ApplicationRunner {


@Autowired
private Environment environment;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Employee Details");
System.out.println("---------------------");
System.out.println("Employee Number : " +
environment.getProperty("employee.eno"));
System.out.println("Employee Name : " +
environment.getProperty("employee.ename"));
System.out.println("Employee Salary : " +
environment.getProperty("employee.esal"));
System.out.println("Employee Address : " +
environment.getProperty("employee.eaddr"));
System.out.println();

System.out.println("Student Details");
System.out.println("----------------------");
System.out.println("Student Id : " +
environment.getProperty("student.sid"));
System.out.println("Student Name : " +
environment.getProperty("student.sname"));
System.out.println("Student Address : " +
environment.getProperty("student.saddr"));
System.out.println();

System.out.println("Customer Details");
System.out.println("-----------------------");
System.out.println("Customer Id : " +
environment.getProperty("customer.cid"));
System.out.println("Customer Name : " +
environment.getProperty("customer.cname"));
System.out.println("Customer Address : " +
environment.getProperty("customer.caddr"));

}
}

App10Application.java
package com.durgasoft.app10;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App10Application {

public static void main(String[] args) {


SpringApplication.run(App10Application.class, args);
}

In Spring Boot applications, we are able to provide the


properties files in the following locations.

1.​Under resources folder.


2.​Under resources / config folder
3.​Under the project folder
4.​Under the project / config folder

In Spring Boot applications, resources and its internal folders


are in the classpath directly but the project folder and its
internal folders except resources are not in the classpath
directly.

If we want to get the properties files which exist in the


resources and its internal folders then we have to use the
following annotation.

@PropertySource(“classpath: filename.properties”)

EX:
@PropertySourrce(“classpath: abc.properties”)
@PropertySourrce(“classpath: ./config/xyz.properties”)

If we want to get the properties files which are not in the


classpath and which are available in a particular location in the
file system then we have to use the following annotation.
EX:
@PropertySource(“file: abc.properties”)
@PropertySource(“file: ./config/xyz.properties”)

If we declare the properties files with the @PropertySources and


@PropertySource annotation then all the properties files data
will be stored inside the Environment Object, from where we can
get all the data.

EX:
resources/a.properties
​message1=This message is from resources/a.properties

resources/config/b.properties
message2=This message is from resources/config/b.properties

app11/c.properties
message3=This message is from app11/c.properties

app11/config/d.properties
message4=This message is from app11/config/d.properties

AppRunner.java
package com.durgasoft.app11.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@PropertySources(
{
@PropertySource("classpath:a.properties"),

@PropertySource("classpath:./config/b.properties"),
@PropertySource("file:c.properties"),
@PropertySource("file:./config/d.properties")
}
)
@Component
public class AppRunner implements ApplicationRunner {

@Autowired
private Environment env;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Message1: " +
env.getProperty("message1"));
System.out.println("Message2: " +
env.getProperty("message2"));
System.out.println("Message3: " +
env.getProperty("message3"));
System.out.println("Message4: " +
env.getProperty("message4"));
}
}

App11Application.java
package com.durgasoft.app11;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App11Application {

public static void main(String[] args) {


SpringApplication.run(App11Application.class, args);
}
}
Message1: This message is from resources/a.properties
Message2: This message is from resources/config/b.properties
Message3: This message is from app11/c.properties
Message4: This message is from app11/config/d.properties

In the Spring Boot application, if we configure multiple


properties files through @PropertySources and @PropertySource
annotations then all the properties files data will be stored
inside the Environment object in an order in which we have
configured the properties files inside the @PropertySources
annotation.

In the above context, if we provide the same key-value pair in


all the properties files then the properties data will be
overridden in an order in which we have configured all the
properties files.

EX:
resources/a.properties
message=This message is from resources/a.properties

resources/config/b.properties
message=This message is from resources/config/b.properties

app11/c.properties
message=This message is from app11/c.properties

app11/config/d.properties
message=This message is from app11/config/d.properties

AppRunner.java
package com.durgasoft.app11.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@PropertySources(
{

@PropertySource("classpath:./config/b.properties"),
@PropertySource("file:./config/d.properties"),
@PropertySource("file:c.properties"),
@PropertySource("classpath:a.properties")

}
)
@Component
public class AppRunner implements ApplicationRunner {

@Autowired
private Environment env;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Message: " +
env.getProperty("message"));

}
}

App11Application.java
package com.durgasoft.app11;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App11Application {

public static void main(String[] args) {


SpringApplication.run(App11Application.class, args);
}

Message: This message is from resources/a.properties


Yaml files:
—-----------
Yaml: Yet Another Markup Language

Yaml is a text representation file to represent data and to


transport data over the network like XML, JSON,....

In general, Yaml files are created with the extension “.yml”.

Inside the Yaml file, we are able to provide the data in the form
of Key-Value pairs with the indentation operator or levels.

In Spring Boot applications, we are able to use the Yaml files as


an alternative to the properties files.

In Spring Boot applications, the default name of the yaml file is


“application.yml” under the resources folder.

EX:
application.properties
server.port=1234
application.name=LoginApplication

application.yml
server:
​ port:8080
application:
​ name:LoginApplication

EX:
In Properties file:
durgasoft.course.name=JAVA
In Yaml File:
durgasoft:
​ course:
​ ​ name:JAVA

EX:
application.yml
server:
port: 1234
application:
name: Demo Project

employee:
eno: 111
ename: Durga
esal: 50000
eaddr: Hyd

student:
sid: S-111
sname: Anil
saddr: Chennai

customer:
cid: C-111
cname: Ramesh
caddr: Pune

Application.java
package com.durgasoft.app12.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Application {
@Value("${server.port}")
private int serverPort;
@Value("${application.name}")
private String applicationName;

public int getServerPort() {


return serverPort;
}

public void setServerPort(int serverPort) {


this.serverPort = serverPort;
}

public String getApplicationName() {


return applicationName;
}

public void setApplicationName(String applicationName) {


this.applicationName = applicationName;
}
}

Employee.java
package com.durgasoft.app12.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Employee {
@Value("${employee.eno}")
private int eno;
@Value("${employee.ename}")
private String ename;
@Value("${employee.esal}")
private float esal;
@Value("${employee.eaddr}")
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

Student.java
package com.durgasoft.app12.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Student {

@Value("${student.sid}")
private String sid;
@Value("${student.sname}")
private String sname;
@Value("${student.saddr}")
private String saddr;

public String getSid() {


return sid;
}

public void setSid(String sid) {


this.sid = sid;
}

public String getSname() {


return sname;
}

public void setSname(String sname) {


this.sname = sname;
}

public String getSaddr() {


return saddr;
}

public void setSaddr(String saddr) {


this.saddr = saddr;
}
}

Customer.java
package com.durgasoft.app12.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Customer {

@Value("${customer.cid}")
private String cid;
@Value("${customer.cname}")
private String cname;
@Value("${customer.caddr}")
private String caddr;

public String getCid() {


return cid;
}

public void setCid(String cid) {


this.cid = cid;
}

public String getCname() {


return cname;
}

public void setCname(String cname) {


this.cname = cname;
}

public String getCaddr() {


return caddr;
}

public void setCaddr(String caddr) {


this.caddr = caddr;
}
}

AppRunner.java
package com.durgasoft.app12.runner;
import com.durgasoft.app12.beans.Application;
import com.durgasoft.app12.beans.Customer;
import com.durgasoft.app12.beans.Employee;
import com.durgasoft.app12.beans.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import org.springframework.stereotype.Component;
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
private Application application;

@Autowired
private Employee employee;

@Autowired
private Student student;

@Autowired
private Customer customer;

@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Application Details");
System.out.println("------------------------");
System.out.println("Application Name : " +
application.getApplicationName());
System.out.println("Server Port Number : " +
application.getServerPort());
System.out.println();

System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
System.out.println();

System.out.println("Student Details");
System.out.println("-------------------------");
System.out.println("Student Id :
"+student.getSid());
System.out.println("Student Name :
"+student.getSname());
System.out.println("Student Address :
"+student.getSaddr());
System.out.println();

System.out.println("Customer Details");
System.out.println("-------------------------");
System.out.println("Customer Id :
"+customer.getCid());
System.out.println("Customer Name :
"+customer.getCname());
System.out.println("Customer Address :
"+customer.getCaddr());
}
}

App12Application.java
package com.durgasoft.app12;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App12Application {

public static void main(String[] args) {


SpringApplication.run(App12Application.class, args);
}

Application Details
------------------------
Application Name : Demo Project
Server Port Number : 1234

Employee Details
------------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000.0
Employee Address : Hyd

Student Details
-------------------------
Student Id : S-111
Student Name : Anil
Student Address : Chennai

Customer Details
-------------------------
Customer Id : C-111
Customer Name : Ramesh
Customer Address : Pune

EX:
application.yml
server:
port: 1234
application:
name: Demo Project

employee:
eno: 111
ename: Durga
esal: 50000
eaddr: Hyd

student:
sid: S-111
sname: Anil
saddr: Chennai

customer:
cid: C-111
cname: Ramesh
caddr: Pune

AppRunner.java
package com.durgasoft.app12.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class AppRunner implements ApplicationRunner {

@Autowired
private Environment env;

@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Application Details");
System.out.println("------------------------");
System.out.println("Application Name : " +
env.getProperty("application.name"));
System.out.println("Server Port Number : " +
env.getProperty("server.port"));
System.out.println();

System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee Number :
"+env.getProperty("employee.eno"));
System.out.println("Employee Name :
"+env.getProperty("employee.ename"));
System.out.println("Employee Salary :
"+env.getProperty("employee.esal"));
System.out.println("Employee Address :
"+env.getProperty("employee.eaddr"));
System.out.println();

System.out.println("Student Details");
System.out.println("-------------------------");
System.out.println("Student Id :
"+env.getProperty("student.sid"));
System.out.println("Student Name :
"+env.getProperty("student.sname"));
System.out.println("Student Address :
"+env.getProperty("student.saddr"));
System.out.println();

System.out.println("Customer Details");
System.out.println("-------------------------");
System.out.println("Customer Id :
"+env.getProperty("customer.cid"));
System.out.println("Customer Name :
"+env.getProperty("customer.cname"));
System.out.println("Customer Address :
"+env.getProperty("customer.caddr"));
}
}

App12Application.java
package com.durgasoft.app12;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App12Application {

public static void main(String[] args) {


SpringApplication.run(App12Application.class, args);
}

Application Details
--------------------
Application Name : Demo Project
Server Port Number : 1234

Employee Details
------------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000
Employee Address : Hyd

Student Details
-------------------------
Student Id : S-111
Student Name : Anil
Student Address : Chennai

Customer Details
-------------------------
Customer Id : C-111
Customer Name : Ramesh
Customer Address : Pune

In a Spring Boot application, if we provide data in multiple yaml


files then we have to import all the yaml files into the
application.yml file in order to get the data from all the yaml
files to the Environment object by using the following property.

spring:
Config:
import:
-​ file1.yml
-​ file2.yml
-​ file3.yml

EX:
application.yml
spring:
config:
import:
- app.yml
- employee.yml
- student.yml
- customer.yml

employee.yml
employee:
eno: 111
ename: Durga
esal: 50000
eaddr: Hyd

student.yml
student:
sid: S-111
sname: Anil
saddr: Chennai

customer.yml
customer:
cid: C-111
cname: Ramesh
caddr: Pune

AppRunner.java
package com.durgasoft.app12.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class AppRunner implements ApplicationRunner {

@Autowired
private Environment env;

@Override
public void run(ApplicationArguments args) throws Exception {

System.out.println("Application Details");
System.out.println("------------------------");
System.out.println("Application Name : " +
env.getProperty("application.name"));
System.out.println("Server Port Number : " +
env.getProperty("server.port"));
System.out.println();

System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee Number :
"+env.getProperty("employee.eno"));
System.out.println("Employee Name :
"+env.getProperty("employee.ename"));
System.out.println("Employee Salary :
"+env.getProperty("employee.esal"));
System.out.println("Employee Address :
"+env.getProperty("employee.eaddr"));
System.out.println();

System.out.println("Student Details");
System.out.println("-------------------------");
System.out.println("Student Id :
"+env.getProperty("student.sid"));
System.out.println("Student Name :
"+env.getProperty("student.sname"));
System.out.println("Student Address :
"+env.getProperty("student.saddr"));
System.out.println();

System.out.println("Customer Details");
System.out.println("-------------------------");
System.out.println("Customer Id :
"+env.getProperty("customer.cid"));
System.out.println("Customer Name :
"+env.getProperty("customer.cname"));
System.out.println("Customer Address :
"+env.getProperty("customer.caddr"));
}
}

App12Application.java
package com.durgasoft.app12;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App12Application {

public static void main(String[] args) {


SpringApplication.run(App12Application.class, args);
}

Application Details
------------------------
Application Name : Demo Project
Server Port Number : 1234
Employee Details
------------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000
Employee Address : Hyd

Student Details
-------------------------
Student Id : S-111
Student Name : Anil
Student Address : Chennai

Customer Details
-------------------------
Customer Id : C-111
Customer Name : Ramesh
Customer Address : Pune

If the yml files exist in different locations like under


classpath or under the file system then we have to use
“classpath” prefix for the yaml files which exists in the
classpath locations and we have to use “file” prefix for the yaml
files which exists in the file system and which are not exists in
the classpath while importing all the yaml files.

EX:
application.yml
spring:
config:
import:
- classpath:app.yml
- classpath:./config/employee.yml
- file:./config/student.yml
- file:customer.yml

resources/app.yml
server:
port: 1234
application:
name: Demo Project

resources/config/employee.yml
employee:
eno: 111
ename: Durga
esal: 50000
eaddr: Hyd

app12/customer.yml
customer:
cid: C-111
cname: Ramesh
caddr: Pune

app12/config/student.yml
student:
sid: S-111
sname: Anil
saddr: Chennai

AppRunner.java
package com.durgasoft.app12.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class AppRunner implements ApplicationRunner {

@Autowired
private Environment env;

@Override
public void run(ApplicationArguments args) throws Exception {

System.out.println("Application Details");
System.out.println("------------------------");
System.out.println("Application Name : " +
env.getProperty("application.name"));
System.out.println("Server Port Number : " +
env.getProperty("server.port"));
System.out.println();

System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee Number :
"+env.getProperty("employee.eno"));
System.out.println("Employee Name :
"+env.getProperty("employee.ename"));
System.out.println("Employee Salary :
"+env.getProperty("employee.esal"));
System.out.println("Employee Address :
"+env.getProperty("employee.eaddr"));
System.out.println();

System.out.println("Student Details");
System.out.println("-------------------------");
System.out.println("Student Id :
"+env.getProperty("student.sid"));
System.out.println("Student Name :
"+env.getProperty("student.sname"));
System.out.println("Student Address :
"+env.getProperty("student.saddr"));
System.out.println();

System.out.println("Customer Details");
System.out.println("-------------------------");
System.out.println("Customer Id :
"+env.getProperty("customer.cid"));
System.out.println("Customer Name :
"+env.getProperty("customer.cname"));
System.out.println("Customer Address :
"+env.getProperty("customer.caddr"));
}
}

App12Application.java
package com.durgasoft.app12;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App12Application {

public static void main(String[] args) {


SpringApplication.run(App12Application.class, args);
}

Application Details
------------------------
Application Name : Demo Project
Server Port Number : 1234

Employee Details
------------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000
Employee Address : Hyd

Student Details
-------------------------
Student Id : S-111
Student Name : Anil
Student Address : Chennai

Customer Details
-------------------------
Customer Id : C-111
Customer Name : Ramesh
Customer Address : Pune

In Spring Boot applications, in the properties we can provide


more than one value for a single property and we will get it into
the Spring Boot application.
In the property file, to provide more than one value to a single
property by using , separator, but all those values will be
stored in the form of String[] in the java classes.

EX:
application.properties
user.name=Durga
user.address=Hyderabad
user.qualifications=BTech,MTech,PHD
user.technologies=JAVA,PYTHON,DEVOPS

User.java
package com.durgasoft.app12.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class User {

@Value("${user.name}")
private String userName;
@Value("${user.address}")
private String userAddress;
@Value("${user.qualifications}")
private String[] userQualifications;
@Value("${user.technologies}")
private String[] userTechnologies;

public String getUserName() {


return userName;
}

public void setUserName(String userName) {


this.userName = userName;
}

public String getUserAddress() {


return userAddress;
}

public void setUserAddress(String userAddress) {


this.userAddress = userAddress;
}

public String[] getUserQualifications() {


return userQualifications;
}

public void setUserQualifications(String[] userQualifications)


{
this.userQualifications = userQualifications;
}

public String[] getUserTechnologies() {


return userTechnologies;
}

public void setUserTechnologies(String[] userTechnologies) {


this.userTechnologies = userTechnologies;
}
}

AppRunner.java
package com.durgasoft.app12.runner;
import com.durgasoft.app12.beans.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class AppRunner implements ApplicationRunner {

@Autowired
private User user;

@Override
public void run(ApplicationArguments args) throws Exception {
String[] userQualifications =
user.getUserQualifications();
String uqual = "";
for (String str : userQualifications) {
uqual += str + " ";
}
String[] userTechnologies = user.getUserTechnologies();
String utech = "";
for (String str : userTechnologies) {
utech += str + " ";
}
System.out.println("User Details");
System.out.println("------------------");
System.out.println("User Name : " +
user.getUserName());
System.out.println("User Address : " +
user.getUserAddress());
System.out.println("User Qualifications : " + uqual);
System.out.println("User Technologies : " + utech);
}
}
App12Application.java
package com.durgasoft.app12;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App12Application {

public static void main(String[] args) {


SpringApplication.run(App12Application.class, args);
}

User Details
------------------
User Name : nagoorn
User Address : Hyderabad
User Qualifications : BTech MTech PHD
User Technologies : JAVA PYTHON DEVOPS

In a Spring Boot application, if we want to provide more than one


value for any property in the yml file then we have to use the
following syntax.

propertyName:
-​ Val1
-​ Val2
-​ val3

Note: in the latest versions of the Spring boot, we can provide


the multiple values to a single property in the following way.

propertyName:
Val1
Val2
val3

EX:
application.yml
user:
name: Durga
address: Hyderabad
qualifications:
BTech
MTech
PHD
technologies:
JAVA
PYTHON
DEVOPS

User.java
package com.durgasoft.app12.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class User {

@Value("${user.name}")
private String userName;
@Value("${user.address}")
private String userAddress;
@Value("${user.qualifications}")
private String[] userQualifications;
@Value("${user.technologies}")
private String[] userTechnologies;

public String getUserName() {


return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}

public String getUserAddress() {


return userAddress;
}

public void setUserAddress(String userAddress) {


this.userAddress = userAddress;
}

public String[] getUserQualifications() {


return userQualifications;
}

public void setUserQualifications(String[] userQualifications)


{
this.userQualifications = userQualifications;
}

public String[] getUserTechnologies() {


return userTechnologies;
}

public void setUserTechnologies(String[] userTechnologies) {


this.userTechnologies = userTechnologies;
}
}

AppRunner.java
package com.durgasoft.app12.runner;

import com.durgasoft.app12.beans.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class AppRunner implements ApplicationRunner {

@Autowired
private User user;

@Override
public void run(ApplicationArguments args) throws Exception {

String[] uquals = user.getUserQualifications();


String uqual = "";
for(String str : uquals) {
uqual += str + "\t";
}
String[] utechs = user.getUserTechnologies();
String utech = "";
for(String str : utechs) {
utech += str + "\t";
}
System.out.println("User Details");
System.out.println("------------------");
System.out.println("User Name : " +
user.getUserName());
System.out.println("User Address : " +
user.getUserAddress());
System.out.println("User Qualifications : " + uqual);
System.out.println("User Technologies : " + utech);
}
}

App12Application.java
package com.durgasoft.app12;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App12Application {

public static void main(String[] args) {


SpringApplication.run(App12Application.class, args);
}

User Details
------------------
User Name : nagoorn
User Address : Hyderabad
User Qualifications : BTech MTech PHD​
User Technologies : JAVA PYTHON DEVOPS

Spring Boot Profiles:


—---------------------
In general, all the projects are prepared by following project
lifecycle stages.

Development
Testing
Production
—---
—---

In Software project development, we have to provide a separate


environment for each and every lifecycle phase, here the
environment means the configurations like Server configurations,
Database Configurations,....

In the above context, configurations are varied from environment


to environment, to switch the project from one environment to
another environment and to provide configurations as per the
environments if we use manual approach, it will be a difficult
process for the developers to provide configurations as per the
project lifecycle phase and there is no guarantee for the
configurations.

To overcome the above problem, Spring Boot has provided a


solution in the form of Spring Boot Profiles.

Profile is an environment, it contains all the configurations


related to the environment.

To implement profiling in the Spring Boot applications we have to


use the following steps.

1. Create a Separate properties file for each and every


Environment:

Properties file name format: application-profileName.properties


EX:
application.properties for the default Environment.
application-dev.properties for the Development Environment
application-test.properties for the Testing Environment
application-prod.properties for the Production Environment

2. Provide the Active Profile:


To provide the active profile we will use the following
approaches.

1.​By using the application.properties:


spring.profiles.active=dev

2.​By using System properties:


System.setProperty(“spring.profiles.active”, “test”);

The above instruction must be provided in the Spring Boot


entry class and before the SpringApplication.run(--).

3.​By Using the Application Arguments in the run


configurations:
– –spring.profiles.active=dev

3. Run the Spring Boot Application.

EX:
application.properties
spring.profiles.active=prod

application-dev.properties
spring.application.name=ICICI Application - DEV Environment
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ICICI-DEV-DB
spring.datasource.username=icici-dev-uname
spring.datasource.password=icici-dev-pwd

application-test.properties
spring.application.name=ICICI Application - TEST Environment
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ICICI-TEST-DB
spring.datasource.username=icici-test-uname
spring.datasource.password=icici-test-pwd

application-prod.properties
spring.application.name=ICICI Application - PROD Environment
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ICICI-PROD-DB
spring.datasource.username=icici-prod-uname
spring.datasource.password=icici-prod-pwd

ProfilesEnvironment.java
package com.durgasoft.app13.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ProfilesEnvironment {
@Value("${spring.application.name}")
private String applicationName;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.url}")
private String driverUrl;
@Value("${spring.datasource.username}")
private String databaseUserName;
@Value("${spring.datasource.password}")
private String databasePassword;

public String getApplicationName() {


return applicationName;
}

public void setApplicationName(String applicationName) {


this.applicationName = applicationName;
}

public String getDriverClassName() {


return driverClassName;
}

public void setDriverClassName(String driverClassName) {


this.driverClassName = driverClassName;
}

public String getDriverUrl() {


return driverUrl;
}

public void setDriverUrl(String driverUrl) {


this.driverUrl = driverUrl;
}

public String getDatabaseUserName() {


return databaseUserName;
}

public void setDatabaseUserName(String databaseUserName) {


this.databaseUserName = databaseUserName;
}

public String getDatabasePassword() {


return databasePassword;
}

public void setDatabasePassword(String databasePassword) {


this.databasePassword = databasePassword;
}
}

ProfilesRunner.java
package com.durgasoft.app13.runner;

import com.durgasoft.app13.beans.ProfilesEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ProfilesRunner implements ApplicationRunner {
@Autowired
ProfilesEnvironment profilesEnvironment;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Application Configuration Details");

System.out.println("--------------------------------------");
System.out.println("Application Name : " +
profilesEnvironment.getApplicationName());
System.out.println("Driver Class Name : " +
profilesEnvironment.getDriverClassName());
System.out.println("Driver URL : " +
profilesEnvironment.getDriverUrl());
System.out.println("Database User Name : " +
profilesEnvironment.getDatabaseUserName());
System.out.println("Database Password : " +
profilesEnvironment.getDatabasePassword());
}
}

Application Configuration Details


--------------------------------------
Application Name : ICICI Application - PROD Environment
Driver Class Name : com.mysql.cj.jdbc.Driver
Driver URL : jdbc:mysql://localhost:3306/ICICI-PROD-DB
Database User Name : icici-prod-uname
Database Password : icici-prod-pwd

Spring Boot Profiles with yml files:


—-------------------------------------
If we want to provide Spring boot profiles with YAML files then
we will use a single YAML file and we will provide all the
profile configurations in the single YAML file with the following
syntax.

application.yml
—---------------
spring:
profiles:
active: prod

—--
spring:
config:
profiles-on: dev
—---- Dev Configurations—---

—--
spring:
config:
profiles-on: test
—---- Test Configurations—---

—--
spring:
config:
profiles-on: prod
—---- Prod Configurations—---

EX:
application.yml
spring:
profiles:
active: test
---
spring:
config:
activate:
on-profile: dev

application:
name: ICICI Application - DEV Environment

datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ICICI-DEV-DB
username: icici-dev-uname
password: icici-dev-pwd
---
spring:
config:
activate:
on-profile: test

application:
name: ICICI Application - TEST Environment

datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ICICI-TEST-DB
username: icici-test-uname
password: icici-test-pwd
---
spring:
config:
activate:
on-profile: prod

application:
name: ICICI Application - PROD Environment

datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ICICI-PROD-DB
username: icici-prod-uname
password: icici-prod-pwd

ProfileEnvironment.java
package com.durgasoft.app13.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ProfilesEnvironment {
@Value("${spring.application.name}")
private String applicationName;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.url}")
private String driverUrl;
@Value("${spring.datasource.username}")
private String databaseUserName;
@Value("${spring.datasource.password}")
private String databasePassword;

public String getApplicationName() {


return applicationName;
}

public void setApplicationName(String applicationName) {


this.applicationName = applicationName;
}
public String getDriverClassName() {
return driverClassName;
}

public void setDriverClassName(String driverClassName) {


this.driverClassName = driverClassName;
}

public String getDriverUrl() {


return driverUrl;
}

public void setDriverUrl(String driverUrl) {


this.driverUrl = driverUrl;
}

public String getDatabaseUserName() {


return databaseUserName;
}

public void setDatabaseUserName(String databaseUserName) {


this.databaseUserName = databaseUserName;
}

public String getDatabasePassword() {


return databasePassword;
}

public void setDatabasePassword(String databasePassword) {


this.databasePassword = databasePassword;
}
}

ProfilesRunner.java
package com.durgasoft.app13.runner;

import com.durgasoft.app13.beans.ProfilesEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ProfilesRunner implements ApplicationRunner {
@Autowired
ProfilesEnvironment profilesEnvironment;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Application Configuration Details");

System.out.println("--------------------------------------");
System.out.println("Application Name : " +
profilesEnvironment.getApplicationName());
System.out.println("Driver Class Name : " +
profilesEnvironment.getDriverClassName());
System.out.println("Driver URL : " +
profilesEnvironment.getDriverUrl());
System.out.println("Database User Name : " +
profilesEnvironment.getDatabaseUserName());
System.out.println("Database Password : " +
profilesEnvironment.getDatabasePassword());
}
}

App13Application.java
package com.durgasoft.app13;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App13Application {

public static void main(String[] args) {

SpringApplication.run(App13Application.class, args);
}

EX:
application.yml
spring:
profiles:
active: test

application-dev.yml
spring:
config:
activate:
on-profile: dev

application:
name: ICICI Application - DEV Environment

datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ICICI-DEV-DB
username: icici-dev-uname
password: icici-dev-pwd

application-test.yml
spring:
config:
activate:
on-profile: test

application:
name: ICICI Application - TEST Environment

datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ICICI-TEST-DB
username: icici-test-uname
password: icici-test-pwd
application-prod.yml
spring:
config:
activate:
on-profile: prod

application:
name: ICICI Application - PROD Environment

datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ICICI-PROD-DB
username: icici-prod-uname
password: icici-prod-pwd

ProfilesEnvironment.java
package com.durgasoft.app13.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ProfilesEnvironment {
@Value("${spring.application.name}")
private String applicationName;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.url}")
private String driverUrl;
@Value("${spring.datasource.username}")
private String databaseUserName;
@Value("${spring.datasource.password}")
private String databasePassword;

public String getApplicationName() {


return applicationName;
}

public void setApplicationName(String applicationName) {


this.applicationName = applicationName;
}

public String getDriverClassName() {


return driverClassName;
}

public void setDriverClassName(String driverClassName) {


this.driverClassName = driverClassName;
}

public String getDriverUrl() {


return driverUrl;
}

public void setDriverUrl(String driverUrl) {


this.driverUrl = driverUrl;
}

public String getDatabaseUserName() {


return databaseUserName;
}

public void setDatabaseUserName(String databaseUserName) {


this.databaseUserName = databaseUserName;
}

public String getDatabasePassword() {


return databasePassword;
}

public void setDatabasePassword(String databasePassword) {


this.databasePassword = databasePassword;
}
}
ProfilesRunner.java
package com.durgasoft.app13.runner;

import com.durgasoft.app13.beans.ProfilesEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ProfilesRunner implements ApplicationRunner {
@Autowired
ProfilesEnvironment profilesEnvironment;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Application Configuration Details");

System.out.println("--------------------------------------");
System.out.println("Application Name : " +
profilesEnvironment.getApplicationName());
System.out.println("Driver Class Name : " +
profilesEnvironment.getDriverClassName());
System.out.println("Driver URL : " +
profilesEnvironment.getDriverUrl());
System.out.println("Database User Name : " +
profilesEnvironment.getDatabaseUserName());
System.out.println("Database Password : " +
profilesEnvironment.getDatabasePassword());
}
}

App13Application.java
package com.durgasoft.app13;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App13Application {

public static void main(String[] args) {

SpringApplication.run(App13Application.class, args);
}

Spring Boot Data JDBC:


—----------------------
In Spring, if we want to prepare Spring JDBC applications then we
have to use the following steps.

1.​Create a Java project with the Spring JDBC dependencies.


2.​Create a DAO class.
3.​Declare a Jdbcemplate property
4.​Perform the Database operations in the DAO class.
5.​Provide the following configurations in the configuration
file.
Datasource Configuration
JdbcTemplate Configuration
DAO configuration
—---
—---
6.​Access the DAO methods either in the Service class or in the
main class.

In Spring Boot, if we want to prepare a Spring JDBC application


then we have to use the following steps.

1.​Create a Spring Boot Project with the “spring-data-jdbc”,


“mysql-connector”.
2.​In the properties file provide the datasource
configurations.
spring.datasource.driver-class-name
spring.datasource.url
spring.datasource.username
Spring.datasource.password
3.​Prepare a DAO interface and DAO class with the @Repository
annotation.
In DAO class, declare JdbcTemplate property with the
@Autowired annotation.

4.​Prepare a Service interface and a Service class with the


@Service annotation.

Inside the Service Class, declare the DAO Class property


with the @Autowired annotation in order to access the dao
methods.

5.​Prepare a Controller class with the @COntroller annotation.

Inside the controller class, declare Service class property


with the @Autowired annotation in order to access the
Service methods.

6.​Prepare a Runner class and access controller methods.

EX:
application.properties
spring.application.name=app12

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/durgadb
spring.datasource.username=root
spring.datasource.password=root@123

Employee.java
package com.durgasoft.app12.beans;

public class Employee {

private int eno;


private String ename;
private float esal;
private String eaddr;
public int getEno() {
return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

EmployeeRunner.java
package com.durgasoft.app12;

import com.durgasoft.app12.beans.Employee;
import com.durgasoft.app12.controller.EmployeeController;
import com.durgasoft.app12.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class EmployeeRunner implements ApplicationRunner {
@Autowired
private EmployeeController employeeController;
@Override
public void run(ApplicationArguments args) throws Exception {
/*Employee employee = new Employee();
employee.setEno(111);
employee.setEname("Durga");
employee.setEsal(50000);
employee.setEaddr("Hyd");
String status = employeeController.addEmployee(employee);
System.out.println(status);*/

/*Employee employee =
employeeController.searchEmployee(111);
if(employee == null) {
System.out.println("Employee not found");
}else{
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number : " +
employee.getEno());
System.out.println("Employee Name : " +
employee.getEname());
System.out.println("Employee Salary : " +
employee.getEsal());
System.out.println("Employee Address : " +
employee.getEaddr());
}*/

/*Employee employee = new Employee();


employee.setEno(111);
employee.setEname("Venkat");
employee.setEsal(60000);
employee.setEaddr("Chennai");
String status =
employeeController.updateEmployee(employee);
System.out.println(status);*/

String status = employeeController.deleteEmployee(111);


System.out.println(status);
}
}

EmployeeController.java
package com.durgasoft.app12.controller;

import com.durgasoft.app12.beans.Employee;
import com.durgasoft.app12.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class EmployeeController {

@Autowired
private EmployeeService employeeService;

public String addEmployee(Employee employee) {


String status = employeeService.addEmployee(employee);
return status;
}
public Employee searchEmployee(int eno) {
Employee employee = employeeService.searchEmployee(eno);
return employee;
}
public String updateEmployee(Employee employee) {
String status = employeeService.updateEmployee(employee);
return status;
}
public String deleteEmployee(int eno) {
String status = employeeService.deleteEmployee(eno);
return status;
}
}

EmployeeService.java
package com.durgasoft.app12.service;

import com.durgasoft.app12.beans.Employee;

public interface EmployeeService {


public String addEmployee(Employee employee);
public Employee searchEmployee(int eno);
public String updateEmployee(Employee employee);
public String deleteEmployee(int eno);
}

EmployeeServiceImpl.java
package com.durgasoft.app12.service;

import com.durgasoft.app12.beans.Employee;
import com.durgasoft.app12.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
private EmployeeDao employeeDao;

@Override
public String addEmployee(Employee employee) {
String status = employeeDao.add(employee);
return status;
}

@Override
public Employee searchEmployee(int eno) {
Employee employee = employeeDao.search(eno);
return employee;
}

@Override
public String updateEmployee(Employee employee) {
String status = employeeDao.update(employee);
return status;
}

@Override
public String deleteEmployee(int eno) {
String status = employeeDao.delete(eno);
return status;
}
}

EmployeeDao.java
package com.durgasoft.app12.dao;

import com.durgasoft.app12.beans.Employee;

public interface EmployeeDao {


public String add(Employee employee);
public Employee search(int eno);
public String update(Employee employee);
public String delete(int eno);
}

EmployeeDaoImpl.java
package com.durgasoft.app12.dao;

import com.durgasoft.app12.beans.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

@Autowired
private JdbcTemplate jdbcTemplate;

@Override
public String add(Employee employee) {
int rowCount = jdbcTemplate.update("insert into emp1
values (" +
employee.getEno() + ",'" +
employee.getEname() + "'," +
employee.getEsal() + ",'" +
employee.getEaddr() + "')");
String status = "";
if(rowCount == 1){
status = "Employee Insertion SUCCESS";
}else{
status = "Employee Insertion FAILURE";
}
return status;
}

@Override
public Employee search(int eno) {
Employee employee = null;
List<Employee> employeeList = jdbcTemplate.query("select *
from emp1 where eno = "+eno,
(rs, rowNum) -> {
Employee emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getInt("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
}
);
return employeeList.isEmpty() ? null :
employeeList.get(0);
}

@Override
public String update(Employee employee) {
int rowCount = jdbcTemplate.update(
"update emp1 set ENAME = '" +
employee.getEname()+"',"
+ "ESAL = " + employee.getEsal()+","
+ "EADDR = '" + employee.getEaddr()+"'"
+ " where ENO = " + employee.getEno()
);
String status = "";
if(rowCount == 1){
status = "Employee Update SUCCESS";
}else {
status = "Employee Update FAILURE";
}
return status;
}

@Override
public String delete(int eno) {
int rowCount = jdbcTemplate.update("delete from emp1 where
ENO = " + eno);
String status = "";
if(rowCount == 1){
status = "Employee Deletion SUCCESS";
} else {
status = "Employee Deletion FAILURE";
}
return status;
}
}

App12Application.java
package com.durgasoft.app12;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App12Application {

public static void main(String[] args) {


SpringApplication.run(App12Application.class, args);
}

In the above Spring Boot application, we have provided


implementation for all the CRUD methods by taking a DAO
implementation class. In general, in all the Spring Boot
applications, CRUD operations are common , due to this reason
Spring Boot has provided predefined implementations to all the
CRUD operations in the form of an interface “CrudRepository” in
Spring Data JDBC.

CrudRepository has the default methods to perform all the CRUD


operations like below.

save(): To save a record in the database table.


delete(): To delete a record from the Database table.
findById(): To get a particular record on the basis of the PK
value.
findAll(): To get All the Records from the Database table.
—---
—---

If we want to use CrudRepository in the Spring Boot applications


we have to declare an interface and it must be extended from the
CrudRepository interface.

public interface EmployeeRepository extends CrudRepository{


// Here we will get all CRUD operations methods from the
CrudRepository.
}

If we want to use CrudRepository in Spring Boot applications we


have to use the following steps.

1. Create a Spring Boot project with the following dependencies.

Spring data Jdbc


Mysql Connector

2. Create a Table in the database with the Auto_increment feature


to the primary key.

sql>create table emp2(ENO int(3) primary key auto_increment,


ENAME char(10), ESAL float(5), EADDR char(10));
sql>commit;

3. Prepare a Bean class or model class, it must be annotated with


@Table annotation and the id property with the @Id annotation.

@Table(name=”emp2”)
public class Employee{
​ @Id
​ private int eno;
​ —---
​ —---
}

4. Prepare Repository interface by extending CrudRepository.

@Repository
public EmployeeRepository extends CrudRepository<Employee,
Integer>{

}
5. Prepare Service class with the @Service annotation and every
method in the Service class must be annotated with @Transactional
except the read methods.

@Service
public class EmployeeServiceImpl implements EmployeeService{
​ @Autowired
​ public EmployeeRepository employeeRepository;

​ @Transactional
​ public Employee addEmployee(Employee employee){
​ ​
​ }

​ public Employee searchEmployee(int eno){
​ ​ —----
​ }
​ —--
​ @Transactional
​ public String deleteEmployee(int eno){
​ ​ —----
​ }
—-----​

6. Prepare Controller class with @Controller annotation:

@Controller
public class EmployeeController{
​ @Autowired
​ private EmployeeService employeeService;

​ public Employee addEmployee(Employee employee){
​ ​ —----
​ }
​ —-----
}
7. Prepare a Runner class to access all the Controller methods:

@Component
public class EmployeeRunner implements ApplicationRunner{
​ public void run(ApplicationArguments args){
​ ​ —----
​ }
}

EX:
application.properties
spring.application.name=app12

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/durgadb
spring.datasource.username=root
spring.datasource.password=root@123

Employee.java
package com.durgasoft.app12.beans;

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;

@Table(name = "EMP4")
public class Employee {

@Id
private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}

@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
", eaddr='" + eaddr + '\'' +
'}';
}
}

EmployeeRepository.java
package com.durgasoft.app12.dao;

import com.durgasoft.app12.beans.Employee;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends
CrudRepository<Employee, Integer> {

}

EmployeeService.java
package com.durgasoft.app12.service;

import com.durgasoft.app12.beans.Employee;

public interface EmployeeService {


public Employee addEmployee(Employee employee);
public Employee searchEmployee(int eno);
public Employee updateEmployee(Employee employee);
public String deleteEmployee(int eno);
}

EmployeeServiceImpl.java
package com.durgasoft.app12.service;

import com.durgasoft.app12.beans.Employee;
import com.durgasoft.app12.dao.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
private EmployeeRepository employeeRepository;
@Transactional
@Override
public Employee addEmployee(Employee employee) {
Employee employee1 = employeeRepository.save(employee);
return employee1;
}

@Override
public Employee searchEmployee(int eno) {
Employee employee =
employeeRepository.findById(eno).orElse(null);
return employee;
}

@Transactional
@Override
public Employee updateEmployee(Employee employee) {
Employee employee1 = employeeRepository.save(employee);
return employee1;
}

@Transactional
@Override
public String deleteEmployee(int eno) {
employeeRepository.deleteById(eno);
return "Employee Deleted Successfully";
}
}

EmployeeController.java
package com.durgasoft.app12.controller;

import com.durgasoft.app12.beans.Employee;
import com.durgasoft.app12.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class EmployeeController {

@Autowired
private EmployeeService employeeService;

public Employee addEmployee(Employee employee) {


Employee employee1 =
employeeService.addEmployee(employee);
return employee1;
}
public Employee searchEmployee(int eno) {
Employee employee = employeeService.searchEmployee(eno);
return employee;
}
public Employee updateEmployee(Employee employee) {
Employee employee1 =
employeeService.updateEmployee(employee);
return employee1;
}
public String deleteEmployee(int eno) {
String status = employeeService.deleteEmployee(eno);
return status;
}
}

EmployeeRunner.java
package com.durgasoft.app12;

import com.durgasoft.app12.beans.Employee;
import com.durgasoft.app12.controller.EmployeeController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class EmployeeRunner implements ApplicationRunner {
@Autowired
private EmployeeController employeeController;
@Override
public void run(ApplicationArguments args) throws Exception {
//Employee employee = new Employee();
//employee.setEno(111);
/*employee.setEname("Durga");
employee.setEsal(50000);
employee.setEaddr("Hyd");
Employee employee2 =
employeeController.addEmployee(employee);
System.out.println(employee2);*/

/* Employee employee =
employeeController.searchEmployee(2);
System.out.println(employee);*/

/*Employee employee = new Employee();


employee.setEno(1);
employee.setEname("Venkat");
employee.setEsal(60000);
employee.setEaddr("Chennai");
Employee employee2 =
employeeController.updateEmployee(employee);
System.out.println(employee2);*/

String status = employeeController.deleteEmployee(1);


System.out.println(status);
}
}

App12Application.java
package com.durgasoft.app12;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App12Application {
public static void main(String[] args) {
SpringApplication.run(App12Application.class, args);
}

In database:
create table EMP4(
ENO int(5) primary key auto_increment,
ENAME char(10),
ESAL float(5),
EADDR char(10)
);
commit ;

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.durgasoft</groupId>
<artifactId>app12</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app12</name>
<description>app12</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
In Spring Boot Data Jdbc, we will use the CrudRepository
interface to get all the predefined methods to perform the
database operations like save(), findById(), deleteById(),....,
but as per the application requirements we want to perform some
database operations which are not defined in the CrudRepository
interface, in this context we are able to define our own methods
in the Repository interface.

To define our own methods in the Repository we will use @Query


annotation with the sql query along with the user defined method,
if the database operation is non select operation then we must
use @Modifying annotation along with the method, if the database
operation is select operation then it is not required to use
@Modifying annotation.

EX:
@Modifying
@Query(“update…..”)
public int update(----);

EX:
@Query(“select….”)
public int findByEmail(---);

EX:
application.properties
spring.application.name=app12

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/durgadb
spring.datasource.username=root
spring.datasource.password=root@123

Employee.java
package com.durgasoft.app12.beans;

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;
@Table(name = "EMP4")
public class Employee {

@Id
private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}

@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
", eaddr='" + eaddr + '\'' +
'}';
}
}

App12Application.java
package com.durgasoft.app12;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App12Application {

public static void main(String[] args) {


SpringApplication.run(App12Application.class, args);
}

EmployeeRunner.java
package com.durgasoft.app12;

import com.durgasoft.app12.beans.Employee;
import com.durgasoft.app12.controller.EmployeeController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class EmployeeRunner implements ApplicationRunner {
@Autowired
private EmployeeController employeeController;
@Override
public void run(ApplicationArguments args) throws Exception {
//Employee employee = new Employee();
//employee.setEno(111);
/*employee.setEname("Durga");
employee.setEsal(50000);
employee.setEaddr("Hyd");
Employee employee2 =
employeeController.addEmployee(employee);
System.out.println(employee2);*/

/* Employee employee =
employeeController.searchEmployee(2);
System.out.println(employee);*/

Employee employee = new Employee();


employee.setEno(2);
employee.setEname("Venkat");
employee.setEsal(60000);
employee.setEaddr("Chennai");
int rowCount =
employeeController.updateEmployee(employee);
if(rowCount == 1) {
System.out.println("Employee updated successfully");
}else {
System.out.println("Employee update failed");
}

/*String status = employeeController.deleteEmployee(1);


System.out.println(status);*/
}
}

EmployeeController.java
package com.durgasoft.app12.controller;
import com.durgasoft.app12.beans.Employee;
import com.durgasoft.app12.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class EmployeeController {

@Autowired
private EmployeeService employeeService;

public Employee addEmployee(Employee employee) {


Employee employee1 =
employeeService.addEmployee(employee);
return employee1;
}
public Employee searchEmployee(int eno) {
Employee employee = employeeService.searchEmployee(eno);
return employee;
}
public int updateEmployee(Employee employee) {
int rowCount = employeeService.updateEmployee(employee);
return rowCount;
}
public String deleteEmployee(int eno) {
String status = employeeService.deleteEmployee(eno);
return status;
}
}

EmployeeService.java
package com.durgasoft.app12.service;

import com.durgasoft.app12.beans.Employee;

public interface EmployeeService {


public Employee addEmployee(Employee employee);
public Employee searchEmployee(int eno);
public int updateEmployee(Employee employee);
public String deleteEmployee(int eno);
}

EmployeeServiceImpl.java
package com.durgasoft.app12.service;

import com.durgasoft.app12.beans.Employee;
import com.durgasoft.app12.dao.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
private EmployeeRepository employeeRepository;

@Transactional
@Override
public Employee addEmployee(Employee employee) {
Employee employee1 = employeeRepository.save(employee);
return employee1;
}

@Override
public Employee searchEmployee(int eno) {
Employee employee =
employeeRepository.findById(eno).orElse(null);
return employee;
}

@Override
public int updateEmployee(Employee employee) {
int rowCount = employeeRepository.update(
employee.getEno(),
employee.getEname(),
employee.getEsal(),
employee.getEaddr()
);
return rowCount;
}

@Transactional
@Override
public String deleteEmployee(int eno) {
employeeRepository.deleteById(eno);
return "Employee Deleted Successfully";
}
}

EmployeeRepository.java
package com.durgasoft.app12.dao;

import com.durgasoft.app12.beans.Employee;
import org.springframework.data.jdbc.repository.query.Modifying;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends
CrudRepository<Employee, Integer> {
@Modifying
@Query("update EMP4 set ENAME=:ename, ESAL=:esal, EADDR=:eaddr
where ENO=:eno")
public Integer update(int eno, String ename, float esal,
String eaddr);
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.durgasoft</groupId>
<artifactId>app12</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app12</name>
<description>app12</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

EX:
application.properties
spring.application.name=app13

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/durgadb
spring.datasource.username=root
spring.datasource.password=root@123

Student.java
package com.durgasoft.app13.beans;

public class Student {

private String sid;


private String sname;
private String saddr;
public String getSid() {
return sid;
}

public void setSid(String sid) {


this.sid = sid;
}

public String getSname() {


return sname;
}

public void setSname(String sname) {


this.sname = sname;
}

public String getSaddr() {


return saddr;
}

public void setSaddr(String saddr) {


this.saddr = saddr;
}

@Override
public String toString() {
return "Student{" +
"sid='" + sid + '\'' +
", sname='" + sname + '\'' +
", saddr='" + saddr + '\'' +
'}';
}
}

StudentRepository.java
package com.durgasoft.app13.repository;

import com.durgasoft.app13.beans.Student;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends
CrudRepository<Student, String> {
}

StudentService.java
package com.durgasoft.app13.service;

import com.durgasoft.app13.beans.Student;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

public interface StudentService {


public Iterable<Student> getAllStudents();
}

StudentServiceImpl.java
package com.durgasoft.app13.service;

import com.durgasoft.app13.beans.Student;
import com.durgasoft.app13.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

@Autowired
private StudentRepository studentRepository;

@Override
public Iterable<Student> getAllStudents() {
Iterable<Student> iterable = studentRepository.findAll();

return iterable;
}
}

StudentController.java
package com.durgasoft.app13.controller;

import com.durgasoft.app13.beans.Student;
import com.durgasoft.app13.repository.StudentRepository;
import com.durgasoft.app13.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class StudentController {
@Autowired
private StudentService studentService;
public Iterable<Student> getAllStudents() {
Iterable<Student> iterable =
studentService.getAllStudents();
return iterable;
}
}

StudentRunner.java
package com.durgasoft.app13.runner;

import com.durgasoft.app13.beans.Student;
import com.durgasoft.app13.controller.StudentController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Iterator;
@Component
public class StudentRunner implements ApplicationRunner {
@Autowired
private StudentController studentController;
@Override
public void run(ApplicationArguments args) throws Exception {
Iterable<Student> iterable =
studentController.getAllStudents();
Iterator<Student> iterator = iterable.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student);
}
}
}

PagingAndSortingRepository:
—--------------------------
The main purpose of the PagingAndSortingRepository is to sort all
the results as per the pagination.

Where sorting means to get all records as per a particular order


like Ascending or descending order.

Where pagination means arranging the results in the multiple


pages.

In Spring Boot Data JDBC applications, if we want to sort all the


results then we have to use the “Sort” class like below.

Sort sort = Sort.by(Sort.Direction.fromString(“ASC”), “saddr”);


Iterable<Employee> iterable = employeeRepository.findAll(sort);

Where the “by()” method is able to define the Sorting order like
Ascending or Descending and the parameter on which we want to
perform sorting.
To get all results from the Database table in a particular
sorting order we will use the following method.

public Iterable findAll(Sort sort)

In Spring Boot Data JDBC applications, if we want to get all


results page by page then we have to use the libraries like
PageRequest and Page like below.

PageRequest pageRequest = PageRequest.of(0,3);


Page<Employee> page = employeeRepository.findAll(pageRequest);
List<Employee> employeeList = page.stream().toList();

Where the “PageRequest” is able to manage the pageNumber and the


number of results in the respective page by using the following
method.

public static PageRequest of(int pageNo, String noOfRecords)

Where the “Page” object is able to manage the records which are
retrieved as per the PageRequest object provided pageNumber and
thenumberOfRecords.

To get the Page object we have to use findAll() method from the
Repository interface.

public Page findAll(PageRequest pageRequest)

If we want to get all the generated results in the form of List


we have to use the following code.

List<Employee> empList = page.stream().toList();

In Spring Boot data JDBC applications, if we want to read all


results page by page as per the pagination with a particular
Sorting order then we have to use the following code.

PageRequest pageRequest = PageRequest.of(


0,
3,
Sort.Direction.fromString(“ASC”),”ename”
);

Page<Employee> page = employeeRepository.findAll(pageRequest);


List<Employee> employeeList = page.stream().toList();

EX:
application.properties
spring.application.name=app13

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/durgadb
spring.datasource.username=root
spring.datasource.password=root@123

Student.java
package com.durgasoft.app13.beans;

public class Student {

private String sid;


private String sname;
private String saddr;

public String getSid() {


return sid;
}

public void setSid(String sid) {


this.sid = sid;
}

public String getSname() {


return sname;
}
public void setSname(String sname) {
this.sname = sname;
}

public String getSaddr() {


return saddr;
}

public void setSaddr(String saddr) {


this.saddr = saddr;
}

@Override
public String toString() {
return "Student{" +
"sid='" + sid + '\'' +
", sname='" + sname + '\'' +
", saddr='" + saddr + '\'' +
'}';
}
}

StudentRepository.java
package com.durgasoft.app13.repository;

import com.durgasoft.app13.beans.Student;
import
org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends
PagingAndSortingRepository<Student, String> {
}

StudentService.java
package com.durgasoft.app13.service;

import com.durgasoft.app13.beans.Student;
import java.util.List;

public interface StudentService {


public List<Student> getAllStudents();
}

StudentServiceImpl.java
package com.durgasoft.app13.service;

import com.durgasoft.app13.beans.Student;
import com.durgasoft.app13.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

@Autowired
private StudentRepository studentRepository;

@Override
public List<Student> getAllStudents() {
/*Sort sort = Sort.by(Sort.Direction.fromString("DESC"),
"sname");
Iterable<Student> iterable =
studentRepository.findAll(sort);
List<Student> studentList = (List<Student>) iterable;*/

/*PageRequest pageRequest = PageRequest.of(1, 3);


Page<Student> studentPage =
studentRepository.findAll(pageRequest);
List<Student> studentList =
studentPage.stream().toList();*/

PageRequest pageRequest = PageRequest.of(2, 2,


Sort.Direction.fromString("DESC"),"sname");
Page<Student> studentPage =
studentRepository.findAll(pageRequest);
List<Student> studentList = studentPage.stream().toList();
return studentList;
}
}

StudentCOntroller.java
package com.durgasoft.app13.controller;

import com.durgasoft.app13.beans.Student;
import com.durgasoft.app13.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;

@Controller
public class StudentController {
@Autowired
private StudentService studentService;
public List<Student> getAllStudents() {
List<Student> studentsList =
studentService.getAllStudents();
return studentsList;
}
}

StudentRunner.java
package com.durgasoft.app13.runner;

import com.durgasoft.app13.beans.Student;
import com.durgasoft.app13.controller.StudentController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;

@Component
public class StudentRunner implements ApplicationRunner {
@Autowired
private StudentController studentController;
@Override
public void run(ApplicationArguments args) throws Exception {
List<Student> studentList =
studentController.getAllStudents();
for (Student student : studentList) {
System.out.println(student);
}
}
}

Spring Boot Data JPA:


—---------------------
JPA: Java Persistence API:

JPA is an API, it can be used to perform the Database operations


in the enterprise applications with the ORM implementation tools.

JPA was provided by J2EE along with EJB3.0 version as a


persistence mechanism.

JPA is a specification or an Abstraction provided by the SUN


Microsystems and implemented by the third party vendors like
JBOSS, Eclipse Foundation, Apache, Weblogic,...

JPA is following ORM rules and regulations to implement the data


persistence in the enterprise applications and it was implemented
by the following tools.
1.​Hibernate
2.​Eclipse Link
3.​Open JPA
—----
—----

Note: If we want to use JPA in the enterprise applications then


we have to use either of the above JPA implementations.

If we want to use JPA in enterprise applications we have to use


the following steps.

1.​Create a Java Project with the JPA libraries that is


Hibernate Libraries.
2.​Prepare the Entity class[Bean Class]
3.​Create Mapping File or Use Annotations in the Entity class.
4.​Create a JPA configuration file[Persistence.xml].
5.​Create a Test Application.

Create a java Project with the Following Dependencies:


1.​hibernate-core
2.​mysql-connector

Create an Entity class:

public class Student{


​ private String sid;
​ private String sname;
​ private String saddr;
​ —----
​ —----
}

Create a Mapping file:


Student.xml
<hibernate-mapping>
​ <class name=”com.dss.beans.Student” table=”student”>
​ ​ <id name=”sid” column=”SID”/>
​ ​ <property name=”sname” column=”SNAME”/>
​ ​ <property name=”saddr” column=”SADDR”/>
​ </class>
</hibernate-mapping>

Create JPA configuration File:


It is the same as the Hibernate configuration file , it includes
the following configuration details.

1.​JDBC parameters like Driver class name, driver URL, database


user name, database password…
2.​Dialect configuration
3.​Mapping Configuration
4.​Transactions configurations
—----
—----
The default name of the configuration file is “Persistence.xml”.

<persistence>
​ <persistence-unit name=”mysql”>
​ ​ <mapping-file>Student.xml</mapping-file>
​ ​ ​ ​ ​ Or
​ ​ <class>com.dss.beansStudent</class> for annotations.
​ ​ <properties>
​ ​ ​ <property name=”javax.persistence.jdbc.driver”
​ ​ ​ ​ ​ value=”com.mysql.cj.jdbc.Driver”/>
​ ​ ​ <property name=”javax.persistence.jdbc.url”
​ ​ ​ value=”jdbc:mysql://localhost:3306/durgadb”/>
​ ​ ​ <property name=”javax.persistence.jdbc.user”
​ ​ ​ ​ ​ value=”root”/>
​ ​ ​ <property name=”javax.persistence.jdbc.password”
​ ​ ​ ​ ​ value=”root@123”/>
​ ​ ​ <property name=”hibernate.dialect”
​ ​ ​ ​ value=”org.hibernate.dialect.MySQLDialect”/>
​ ​ </properties>
​ </persistence-unit>
</persistence>

Create a Test Application:


The main purpose of the Test application is to test the
persistence operations in the enterprise applications.

To prepare a test application we have to use the following steps.

1.​Create an EntityManagerFactory Object.


2.​Create an EntityManager object.
3.​Create an EntityTransaction object.
4.​Perform the Persistence operations.
5.​Perform the commit or rollback operations from the
EntityTransaction.
6.​Close the EntityManager and EntityManagerFactory.

Create an EntityManagerFactory object:


EntityManagerFactory is the same as the SessionFactory in
Hibernate, it is able to manage all the Jdbc parameters and it is
able to provide the database connections,....

To create an EntityManagerFactory object we will use the


following method from the Persistence class.

public static EntityManagerFactory


createEntityManagerFactory(String persistenceUnitName)

EX:
EntityManagerFactory factory =
Persistence.createEntityManagerFactory(“mysql”);

2. Create the EntityManager object:


EntityManager is the same as the Session object in Hibernate, it
is able to provide all the persistence methods in order to
perform the persistence operations.

To create an Entitymanager object we have to use the following


method.

public EntityManager createEntityManager()

EX:
EntityManager entityManager = factory.createEntityManager();

3. Create EntityTransaction object:


EntityTransaction is the same as the Transaction object in
Hibernate, it is able to provide the Transaction support in the
applications like commit or rollback operations.
To create an EntityTransaction object we will use the following
method.

public EntityTransaction createEntityTransaction()

EX:
EntityTransaction entityTransaction =
entityManager.createEntityTransaction();

Note: If we use the EntityTransaction in the JPA application then


we have to use either commit or rollback operations after
performing the persistence operations.

public void commit()


public void rollback()

Note: In general, in the JPA applications we will use the


EntityTransaction object for the non select operations only.

Perform the persistence operations:

To perform the persistence operations we will use the following


methods.

public Object find(Class entityType, Serializable pkValue)


public void persist(Object entity)
public void remove(Object entity)

Note: Except the find() method if we use the persist() method ,


remove() method and if we perform update operations then it is
mandatory to use commit or rollback operations.

Close the EntityManager and EntityManagerFactory objects:


entityManager.close();
entityManagerFactory.close();

EX:
Employee.java
package com.durgasoft.beans;

public class Employee {

private int eno;


private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

Employee.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno" column="ENO"/>
<property name="ename" column="ENAME"/>
<property name="esal" column="ESAL"/>
<property name="eaddr" column="EADDR"/>
</class>
</hibernate-mapping>

resources/META-INF/persistence.xml
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
version="3.1"
>
<persistence-unit name="mysql">
<mapping-file>Employee.xml</mapping-file>
<properties>
<property name="jakarta.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver"/>
<property name="jakarta.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/durgadb"/>
<property name="jakarta.persistence.jdbc.user"
value="root"/>
<property name="jakarta.persistence.jdbc.password"
value="root@123"/>
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;

public class Main {


public static void main(String[] args) {
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory("mysql");
EntityManager entityManager =
entityManagerFactory.createEntityManager();
/*EntityTransaction entityTransaction =
entityManager.getTransaction();
entityTransaction.begin();
Employee employee = new Employee();
employee.setEno(111);
employee.setEname("Durga");
employee.setEsal(50000);
employee.setEaddr("Hyd");
entityManager.persist(employee);
entityTransaction.commit();
System.out.println("Employee Inserted Successfully");*/
/*Employee employee = entityManager.find(Employee.class,
222);
if (employee == null) {
System.out.println("Employee not found");
}else{
System.out.println("Employee Details");
System.out.println("----------------------");
System.out.println("Employee Number : " +
employee.getEno());
System.out.println("Employee Name : " +
employee.getEname());
System.out.println("Employee Salary : " +
employee.getEsal());
System.out.println("Employee Address : " +
employee.getEaddr());
}*/
/*EntityTransaction entityTransaction =
entityManager.getTransaction();
entityTransaction.begin();
Employee employee = entityManager.find(Employee.class,
111);
employee.setEname("Durga");
employee.setEsal(50000);
employee.setEaddr("Hyd");
entityManager.persist(employee);
entityTransaction.commit();
System.out.println("Employee Updated Successfully");*/
EntityTransaction entityTransaction =
entityManager.getTransaction();
entityTransaction.begin();
Employee employee = entityManager.find(Employee.class,
111);
entityManager.remove(employee);
entityTransaction.commit();
System.out.println("Employee Removed Successfully");
entityManager.close();
entityManagerFactory.close();
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.durgasoft</groupId>
<artifactId>app14</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding
>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.3.0.CR1</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.3.0</version>
</dependency>
</dependencies>

</project>

Annotations in JPA:
—-------------------
If we want to use Annotations in place of the mapping file we
have to use the following steps.

1. Use the following annotations in the Entity class.

@Entity
@Table
@Id
@Column
2. Configure Annotation class in persistence.xml

<persistence>
​ <persistence-unit name=”mysql”>
​ ​ <class>com.durgasoft.beans.Employee</class>
​ ​ —---
​ </persistence-unit>
</persistence>

EX:
Employee.java
package com.durgasoft.beans;

import jakarta.persistence.*;

@Entity
@Table(name = "emp1")
public class Employee {

@Id
@Column(name="ENO")
private int eno;
@Column(name="ENAME")
private String ename;
@Column(name="ESAL")
private float esal;
@Column(name="EADDR")
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

resources/META-INF/persistence.xml
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
version="3.1"
>
<persistence-unit name="mysql">
<!--<mapping-file>Employee.xml</mapping-file>-->
<class>com.durgasoft.beans.Employee</class>
<properties>
<property name="jakarta.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver"/>
<property name="jakarta.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/durgadb"/>
<property name="jakarta.persistence.jdbc.user"
value="root"/>
<property name="jakarta.persistence.jdbc.password"
value="root@123"/>
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;

public class Main {


public static void main(String[] args) {
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory("mysql");
EntityManager entityManager =
entityManagerFactory.createEntityManager();
/*EntityTransaction entityTransaction =
entityManager.getTransaction();
entityTransaction.begin();
Employee employee = new Employee();
employee.setEno(111);
employee.setEname("Durga");
employee.setEsal(50000);
employee.setEaddr("Hyd");
entityManager.persist(employee);
entityTransaction.commit();
System.out.println("Employee Inserted Successfully");*/
/*Employee employee = entityManager.find(Employee.class,
111);
if (employee == null) {
System.out.println("Employee not found");
}else{
System.out.println("Employee Details");
System.out.println("----------------------");
System.out.println("Employee Number : " +
employee.getEno());
System.out.println("Employee Name : " +
employee.getEname());
System.out.println("Employee Salary : " +
employee.getEsal());
System.out.println("Employee Address : " +
employee.getEaddr());
}*/
/*EntityTransaction entityTransaction =
entityManager.getTransaction();
entityTransaction.begin();
Employee employee = entityManager.find(Employee.class,
111);
employee.setEname("Anil");
employee.setEsal(60000);
employee.setEaddr("Chennai");
entityTransaction.commit();
System.out.println("Employee Updated Successfully");*/
EntityTransaction entityTransaction =
entityManager.getTransaction();
entityTransaction.begin();
Employee employee = entityManager.find(Employee.class,
111);
entityManager.remove(employee);
entityTransaction.commit();
System.out.println("Employee Removed Successfully");
entityManager.close();
entityManagerFactory.close();
}
}

Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app14</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding
>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.3.0.CR1</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.3.0</version>
</dependency>
</dependencies>

</project>

Spring With JPA:


—-----------------
If we want to use JPA in the Spring ORM applications then we have
to use the following steps.

1.​Create a Project with Spring and JPA[Hibernate]


Dependencies.
2.​Create a POJO class.
3.​Create a DAO interface.
4.​Create a DAO implementation class.
5.​Create a Mapping File.
6.​Create Spring Configuration File
7.​Create a Test Application

1. Create a Project with Spring and JPA[Hibernate] Dependencies:

1.​Spring-orm
2.​Hibernate-core
3.​mysql-connector

2. Create a POJO class:

public class Product{


​ private String pid;
​ private String pname;
​ private int pcost;
​ —---
​ —---
}

3. Create a DAO interface:

public interface ProductDao{


​ public String add(Product product);
​ public Product search(String pid);
​ public String update(Product product);
​ public String delete(int pid);
}

4. Create DAO implementation class:

@Repository
public ProductDaoImpl implements ProductDao{
@PersistenceContext​
​ private EntityManager entityManager;

​ public String add(Product product){ }


​ public Product search(String pid){ }
​ public String update(Product product){ }
​ public String delete(int pid){ }
}

5. Create a Mapping File:

<hibernate-mapping>
​ <class name=”com.durgasoft.beans.Product” table=”product”>
​ ​ <id name=”pid”/>
​ ​ <property name=”pname”/>
​ ​ <property name=”pcost”/>
​ </class>
</hibernate-mapping>

6. Create a Spring Configuration File:

In Spring-JPA integration, we have to provide the following


configuration details in the Spring Configuration File.

1.​Datasource Configuration
driverClassName
url
userName
password

2.​EntityManagerFactoryBean:
dataSource
persistenceUnitName
jpaVendorAdaptor
mappingResources
jpaProperties

3.​TransactionManager
entityManagerFactory

4.​ProductDao

EX:
<beans …. >
​ <context:component-scan base-package=”com.durgasoft.*”/>
​ <tx:annotation-driven/>
​ <bean name=”dataSource” class=”org…DriverManagerDataSource”>
​ ​ <property name=”driverClassName”
​ ​ ​ ​ value=”com.mysql.cj.jdbc.Driver”/>
​ ​ <property name=”url”
​ ​ ​ ​ value=”jdbc:mysql://localhost:3306/durgadb”/>
​ ​ <property name=”username” value=”root”/>
​ ​ <property name=”password” value=”root@123”/>
​ </bean>
​ <bean name="entityManagerFactoryBean"
class=”org….LocalContainerEntityManagerFactoryBean”>
<property name=”dataSource” ref=”dataSource”/>
<property name=”persistenceUnit” value=”mysql”/>
<property name=”jpaVendorAdapter”
​ ​ value=”org….HibernateJpaVendorAdapter”/>
<property name=”mappingResources”>
​ <list>
​ ​ <value>Product.xml</value>
​ </list>
</property>
<property name=”jpaProperties”>
​ <props>
​ ​ <prop key=”hibernate.dialect”>
MySQLDialect</prop>
<property key=”hibernate.show_sql”>true</prop>
​ </props>
</property>
</bean>
<bean name=”transactionManager”
class=”org..JpaTransactionManager”>
<property name=”entityManagerFactory”
​ ​ ref=”entityManagerFactoryBean”/>
​ </bean>
​ <bean name=”productDao” class=”com…ProductDao”/>
</beans>
7. Create a Test Application:

public class Test{


​ public static void main(String[] args){
​ ​ ApplicationContext context = new
ClassPathXmlApplicatiounContext(“Spring-Config.xml”);
ProductDao dao = context.geBean(“productDao”);
Product p = new Product();
—---
dao.add(p);
—---
Product p = dao.search(“p1”);
—---
dao.update(p);
—---
dao.delete(“p1”);
​ }
}

EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

Employee.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>

EmployeeDao.java
package com.durgasoft.dao;
import com.durgasoft.beans.Employee;

public interface EmployeeDao {


public String add(Employee employee);
public Employee search(int eno);
public String update(Employee employee);
public String delete(int eno);
}

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {

@PersistenceContext
private EntityManager entityManager;

@Transactional
@Override
public String add(Employee employee) {
String status = "";
Employee emp = entityManager.find(Employee.class,
employee.getEno());
if(emp == null){
entityManager.persist(employee);
status = "Employee inserted Successfully";
}else{
status = "Employee already exists";
}
return status;
}
@Override
public Employee search(int eno) {
Employee employee = entityManager.find(Employee.class,
eno);
return employee;
}

@Transactional
@Override
public String update(Employee employee) {
String status = "";
Employee emp = entityManager.find(Employee.class,
employee.getEno());
if(emp == null){
status = "Employee not found";
}else{
emp.setEname(employee.getEname());
emp.setEsal(employee.getEsal());
emp.setEaddr(employee.getEaddr());
entityManager.persist(emp);
status = "Employee updated successfully";
}
return status;
}

@Transactional
@Override
public String delete(int eno) {
String status = "";
Employee emp = entityManager.find(Employee.class, eno);
if(emp == null){
status = "Employee not found";
}else{
entityManager.remove(emp);
status = "Employee deleted successfully";
}
return status;
}
}
Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContex
t;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("Spring-Config.xml");
EmployeeDao employeeDao = (EmployeeDao)
applicationContext.getBean("employeeDao");

/*Employee employee = new Employee();


employee.setEno(111);
employee.setEname("Durga");
employee.setEsal(50000);
employee.setEaddr("Hyd");
String status = employeeDao.add(employee);
System.out.println(status);*/

/*Employee employee = employeeDao.search(222);


if (employee == null) {
System.out.println("Employee not found");
}else{
System.out.println("Employee Details");
System.out.println("--------------------");
System.out.println("Employee Number : " +
employee.getEno());
System.out.println("Employee Name : " +
employee.getEname());
System.out.println("Employee Salary : " +
employee.getEsal());
System.out.println("Employee Address : " +
employee.getEaddr());
}*/

/*Employee employee = new Employee();


employee.setEno(222);
employee.setEname("Anil");
employee.setEsal(60000);
employee.setEaddr("Chennai");
String status = employeeDao.update(employee);
System.out.println(status);*/

String status = employeeDao.delete(111);


System.out.println(status);
}
}

Spring-Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

<context:component-scan base-package="com.durgasoft.*"/>
<tx:annotation-driven/>
<bean name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSourc
e">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root@123"/>
</bean>
<bean name="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFac
toryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitName" value="mysql"/>
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapt
er"/>
</property>
<property name="mappingResources">
<list>
<value>Employee.xml</value>
</list>
</property>
<property name="jpaProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean name="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactoryBean"/>
</bean>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app15</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding
>
</properties>
<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>6.0.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.2.7.Final</version>
</dependency>
</dependencies>
</project>
Spring Boot Data JPA:
—---------------------
Q)To perform the Database operations with the JPA already we have
Spring ORM module with a very good integration layer for JPA
Persistence mechanism then what is the requirement to use Spring
Boot Data JPA?
—----------------------------------------------------------------
Ans:
—---
1. To perform Database operations if we use the Spring ORM module
with JPA implementations then we must provide implementations for
all the DAO methods like save(), find(), findAll(),
remove(),...in all the DAO implementation classes like
EmployeeDaoImpl, StudentDaoImpl, ProductDaoimpl,... it will
increase boilerplate code.

In the above context, to reduce the boilerplate code we have to


use Spring Data JPA. In Spring boot Data JPA we will not provide
implementation for all the DAO methods, Spring Boot Data JPA will
provide predefined implementations for all the DAO methods in the
form of the Repository interfaces like JpaRepository.

2. In the Spring ORM Module with the JPA implementation we have


to provide more configurations in the configuration files, where
the Configurations include DataSource configurations,
EntityManagerFactoryBean configuration, TransactionManager
CONfiguration, Dao classes Configuration,....

In the case of Spring Boot Data JPA, it is not required to


provide configurations in the configuration file, Spring Boot
follows Auto-Configurations internally, so all the configurations
are provided by Spring Boot Data JPA internally.

3. In Spring ORM Module, we are not having the default embedded


databases internally.

In the case of Spring Boot data JPA, we are able to have the
internal embedded databases like H2, HSQLDB, Apache Derby,...
4. Spring ORM module does not provide inbuilt support for the SQL
and No SQL Databases.

Spring Boot Data JPA provide inbuilt support for the SQL and
NoSQL databases,

5. Spring ORM Module does not provide support for the Query
methods.

Spring Boot Data JPA supports the Query methods.

6. In SPring ORM Module the default connection pooling mechanism


is the low level mechanism “DriverManagerDataSource”, it is not
suggestible for the Production Environment.

In the Spring Boot Data JPA, the default connection pooling


mechanism is “Hikary”, it is a high level mechanism, supporting
the production environment.

Repository Interfaces:
—----------------------
The main purpose of the Repository interfaces is to reduce
boilerplate code , they are able to provide predefined
implementations to all the DAO methods that developers can reuse
in order to perform the database operations.

Spring Boot data JPA has provided the following Repository


interfaces.
In Spring Boot Data JPA , if we want to perform the database
operations we have to declare an user defined interface and it
must be extended from the JpaRepository interface, in this case
the User defined interface has all the methods of the
JpaRepository to perform the database operations.

@Repository
public interface EmployeeRepository extends
JpaRepository<Employee, int>{

Steps to prepare Spring Boot data JPA application:


—-------------------------------------------------
1. Create a database table with a primary key column having
Identity capability.

sql>create table Product(PID int(5) primary key auto_increment,


PNAME char(10), PCOST int(5));
sql>commit;

2. Create a Spring Boot project with the following dependencies.

a.​Spring data Jpa


b.​Spring Web
c.​MySQL Driver

3. Provide the following configurations in the properties file.

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/durgadb
spring.datasource.username=root
spring.datasource.password=root@123
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQLDial
ect
4. Create a Bean class / Model class.

​ public class Product{
​ ​ private int pid;
​ ​ private String pname;
​ ​ private int pcost;
​ ​ —---
​ }

5. Prepare a Repository interface:


a.​Declare an user defined interface.
b.​Extend the user defined interface from JpaRepository
c.​If we want to perform a select operation on the basis of a
particular property then we have to declare the methods with
the following format, no need to provide implementation.

public EntityName findEntityNameByFieldName(propertyName)


EX:
public Product findProductByPname(String pname)
public Product findProductByPcost(int pcost)

d.​In the Repository interface, we can provide our own query


methods as per the requirement by using @Query() annotation.

@Repository
public ProductRepository extends JpaRepository<Product,
int>{

}

6. Prepare Service interface and its implementation class and


access the Repository methods.

a.​Declare an interface with all the service methods.


b.​Provide an implementation class to the Service interface.
c.​Declare Repository property with @Autowired annotation.
d.​Inside the Service methods implementations access the
Repository methods.
EX:
public interface ProductService{
​ public String addProduct(Product product);
​ public Product searchProduct(int pid);
​ public String updateProduct(Product product);
​ public String deleteProduct(int pid);
}

@Service
public class ProductServiceImpl implements ProductService{

​ @Autowired
​ private ProductRepository productRepository;

​ @Transactional
​ public String addProduct(Product product){
​ ​ Product prd = productRepository.save(product);
​ ​ return “success”;
​ }
​ public Product searchProduct(int pid){
​ ​ return productRepository.findById(pid);
​ }
​ @Transactional
​ public String updateProduct(Product product){
​ ​ Product prd =
productRepository.findById(product.getPid());
prd.setPname(product.getPname());
prd.setPcost(product.getPcost());

​ }
​ public String deleteProduct(int pid){
​ ​ productRepository.deleteById(pid);
​ ​ return “success”;
​ }
}
7. Prepare Controller class with the Controller methods and
access the Service methods:

a.​Declare an user defined class with the @Controller


annotation.
b.​Inject Service in the Controller class with @Autowired
annotation.
c.​Provide the Controller methods and access service methods.

EX:
@Controller
public class ProductController{
​ @Autowired
​ private ProductService productService;

​ public String addProduct(Product product){
​ ​ String status = productService.addProduct(product);
​ ​ return status;
​ }
​ public Product getProduct(int pid){
​ ​ Product product = productService.searchProduct(pid);
​ ​ return product;
​ }
​ public String updateProduct(Product product){
​ ​ String status = productService.updateProduct(product);
​ ​ return status;
​ }
​ public String deleteProduct(int pid){
​ ​ String status = productService.deletProduct(pid);
​ ​ return status;
​ }
}

8. Create a Runner class and Access all Controller Methods:

@Component
public class ProductRunner implements ApplicationRunner{
​ @Autowired
​ private ProductController productController;
​ public void run(ApplicationArguments args){
​ ​ Product product = new Product();
​ ​ product.setPid(“P111”);
​ ​ product.setPname(“AAA”);
​ ​ product.setPcost(5000);
​ ​ String status = productController.addProduct(product);
​ ​ System.out.println(status);
​ ​ —----
​ ​ —----
​ }
}

EX:
application.properties
spring.application.name=app16
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/durgadb
spring.datasource.username=root
spring.datasource.password=root@123

spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update

Product.java
package com.durgasoft.app16.beans;

import jakarta.persistence.*;

@Entity
@Table(name="PRODUCT")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="PID", length = 5)
private int pid;

@Column(name="PNAME", length = 20)


private String pname;

@Column(name = "PCOST", length = 5)


private int pcost;

public int getPid() {


return pid;
}

public void setPid(int pid) {


this.pid = pid;
}

public String getPname() {


return pname;
}

public void setPname(String pname) {


this.pname = pname;
}

public int getPcost() {


return pcost;
}

public void setPcost(int pcost) {


this.pcost = pcost;
}

@Override
public String toString() {
return "Product{" +
"pid=" + pid +
", pname='" + pname + '\'' +
", pcost=" + pcost +
'}';
}
}
ProductRunner.java
package com.durgasoft.app16.runner;

import com.durgasoft.app16.ProductController;
import com.durgasoft.app16.beans.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ProductRunner implements ApplicationRunner {

@Autowired
private ProductController productController;
@Override
public void run(ApplicationArguments args) throws Exception {
/*Product product = new Product();
//product.setPid(1);
product.setPname("Mobile");
product.setPcost(50000);
Product prd = productController.addProduct(product);
System.out.println(prd);*/

/*Product product = productController.searchProduct(1);


if (product == null) {
System.out.println("Product not found");
}else{
System.out.println(product);
}*/
/*Product product =
productController.searchProductByPname("Computer");
if (product == null) {
System.out.println("Product not found");
}else{
System.out.println(product);
}*/
/*List<Product> products =
productController.searchProductsByPcost(50000);
for (Product product : products) {
System.out.println(product);
}*/

/*Product product = new Product();


product.setPid(1);
product.setPname("TAB");
product.setPcost(25000);
int rowCount = productController.updateProduct(product);
if(rowCount == 1){
System.out.println("Product Updated Successfully");
}else {
System.out.println("Product Not Updated
Successfully");
}*/

String status = productController.deleteProduct(52);


System.out.println(status);
}
}

ProductController.java
package com.durgasoft.app16;

import com.durgasoft.app16.beans.Product;
import com.durgasoft.app16.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;

@Controller
public class ProductController {
@Autowired
private ProductService productService;
public Product addProduct(Product product) {
Product prd = productService.addProduct(product);
return prd;
}
public Product searchProduct(int pid) {
Product product = productService.searchProduct(pid);
return product;
}
public Product searchProductByPname(String pname) {
Product product =
productService.searchProductByPname(pname);
return product;
}
public List<Product> searchProductsByPcost(int pcost) {
List<Product> products =
productService.searchProductsByPcost(pcost);
return products;
}
public int updateProduct(Product product) {
int rowCount= productService.updateProduct(product);
return rowCount;
}
public String deleteProduct(int pid) {
String status = productService.deleteProduct(pid);
return status;
}
}

ProductService.java
package com.durgasoft.app16.service;

import com.durgasoft.app16.beans.Product;

import java.util.List;

public interface ProductService {


public Product addProduct(Product product);
public Product searchProduct(int pid);
public Product searchProductByPname(String pname);
public List<Product> searchProductsByPcost(int pcost);
public int updateProduct(Product product);
public String deleteProduct(int pid);
}

ProductServiceImpl.java
package com.durgasoft.app16.service;

import com.durgasoft.app16.beans.Product;
import com.durgasoft.app16.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {

@Autowired
private ProductRepository productRepository;

@Transactional
@Override
public Product addProduct(Product product) {
String status = "";
Product prd = productRepository.save(product);
return prd;
}

@Override
public Product searchProduct(int pid) {
Optional<Product> optional =
productRepository.findById(pid);
Product product = optional.get();
return product;
}
@Override
public Product searchProductByPname(String pname) {
Product product =
productRepository.findProductByPname(pname);
return product;
}

@Override
public List<Product> searchProductsByPcost(int pcost) {
List<Product> products =
productRepository.findProductsByPcost(pcost);
return products;
}

@Transactional
@Override
public int updateProduct(Product product) {
int rowCount = productRepository.updateProduct(
product.getPid(),
product.getPname(),
product.getPcost()
);
return rowCount;
}

@Override
public String deleteProduct(int pid) {
String status = "";
Product product = productRepository.findById(pid).get();
if(product == null){
status = "Product not found";
}else{
productRepository.delete(product);
status = "Product deleted successfully";
}
return status;
}
}
ProductRepository.java
package com.durgasoft.app16.repository;

import com.durgasoft.app16.beans.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ProductRepository extends JpaRepository<Product,
Integer> {
public Product findProductByPname(String pname);
public List<Product> findProductsByPcost(int pcost);

@Modifying
@Query("update Product set pname= :pname, pcost= :pcost where
pid= :pid")
public int updateProduct(int pid, String pname, int pcost);
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.durgasoft</groupId>
<artifactId>app16</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app16</name>
<description>app16</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

PagingAndSortingRepository in Spring Boot Data JPA:


—---------------------------------------------------
The main purpose of the PagingAndSortingRepository interface is
to sort all the results as per the Pagination.

In Spring Boot Data JPA applications, if we want to sort all the


results we have to use the “Sort” class.

Sort sort = Sort.by(Sort.Direction.fromString(“ASC”, “saddr”);


Iterable<Student> iterable = studentRepository.findAll(sort);

Where Sort.by() method is able to define the Sorting direction


like Ascending or Descending order on the basis of the provided
property.

To get all results from the Database table in a particular


Sorting order we have to use the following method.

public Iterable findAll(Sort sort)

In Spring Boot data JPA applications, if we want to read all


results in page by page manner we have to use the predefined
libraries like “PageRequest” and “Page”.

PageRequest pageRequest = PageRequest.of(0,3);


Page<Student> page = studentRepository.finadAll(pageRequest);
List<Student> studentsList=page.stream().toList();
Where the “PageRequest” is able to manage the page number and the
number of records in the respective page by using the following
static method.

public static PageRequest of(int pageNo, int noOfRecords)

Where the “Page” object is able to manage the records which are
retrieved as per the PageRequest object provided Page number and
the number of records.

To get the Page object we have to use the following method.

public Page findAll(PageRequest pageRequest);

If we want to get all Results from the Page object to the List
object we have to use the following code.

List<Student> list = page.stream().toList();

In Spring Boot data JPA applications, if we want to read all


results page by page in a particular sorting order then we have
to use the following code.

PageRequest pageRequest =
PageRequest.of(0,3,Sort.Direction.fromString(“DESC”), “sname”);
Page<Student> page = studentRepository.findAll(pageRequest);
List<Student> students = page.stream().toList();

EX:
application.properties
spring.application.name=app17
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/durgadb
spring.datasource.username=root
spring.datasource.password=root@123
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true

Student.java
package com.durgasoft.app17.beans;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name="STUDENT")
public class Student {

@Id
private String sid;
private String sname;
private String saddr;

public String getSid() {


return sid;
}

public void setSid(String sid) {


this.sid = sid;
}

public String getSname() {


return sname;
}

public void setSname(String sname) {


this.sname = sname;
}

public String getSaddr() {


return saddr;
}

public void setSaddr(String saddr) {


this.saddr = saddr;
}
@Override
public String toString() {
return "Student{" +
"sid='" + sid + '\'' +
", sname='" + sname + '\'' +
", saddr='" + saddr + '\'' +
'}';
}
}

StudentRepository.java
package com.durgasoft.app17.repository;

import com.durgasoft.app17.beans.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends JpaRepository<Student,
String> {
}

StudentRunner.java
package com.durgasoft.app17.runner;

import com.durgasoft.app17.beans.Student;
import com.durgasoft.app17.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class StudentRunner implements ApplicationRunner {

@Autowired
private StudentRepository studentRepository;

@Override
public void run(ApplicationArguments args) throws Exception {

/*Sort sort = Sort.by(Sort.Direction.fromString("DESC"),


"sname");
List<Student> studentsList =
studentRepository.findAll(sort);
for (Student student : studentsList) {
System.out.println(student);
}*/

/*PageRequest pageRequest = PageRequest.of(1, 3);


Page<Student> page =
studentRepository.findAll(pageRequest);
List<Student> students = page.stream().toList();
for (Student student : students) {
System.out.println(student);
}*/

PageRequest pageRequest = PageRequest.of(0, 3,


Sort.Direction.fromString("DESC"),"saddr");
Page<Student> page =
studentRepository.findAll(pageRequest);
List<Student> students = page.stream().toList();
for (Student student : students) {
System.out.println(student);
}
}
}

App17Application.java
package com.durgasoft.app17;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App17Application {

public static void main(String[] args) {


SpringApplication.run(App17Application.class, args);
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.durgasoft</groupId>
<artifactId>app17</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app17</name>
<description>app17</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
In Memory Databases in Spring Boot:
—------------------------------------
In Enterprise applications, if we want to use the Traditional
databases like Oracle, MySQL,...then we have to use the following
steps.

1.​Install the Database Software.


2.​Provide the Database Configurations.
3.​Create Schemas.
4.​Create Tables.
5.​Populate the Data in tables.
6.​Create Datasources to connect from the applications to the
Database.
—----
—----
—----
All the above steps in our applications are difficult to test the
applications, in this context, to test the applications without
using all the above steps we will use “in Memory Databases”.

In Memory databases are able to provide the following advantages.

1.​Zero project setup and Infrastructure.


2.​Zero Configurations in our systems.
3.​Zero maintenance.
4.​Easy to use
—---
—---

Spring Boot data JPA supports the In Memory Databases like H2,
Derby,...

In Spring Boot applications, if we use In-Memory databases then


the Database will be created at the time of loading the Spring
Boot application and it will be terminated at the time of
terminating the Spring Boot application.

H2 is a Relational Database Management System, it is embedded in


the SPring Boot internally.
If we want to use the H2 database for the Spring Boot
applications then we have to use the following steps.

1.​Create a Spring boot Project with the following


dependencies.

Spring WEB, h2, Data JPA

2.​Provide the H2 database configurations in the properties


file.

spring.datasource.driver-class–name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:durgadb
spring.datasource.username=sa
spring.datasource,password=sa
spring.h2.console.enabled=true

3.​Create a Bean class:

@Entity
public class Employee{
​ @Id
​ @GeneratedValue
​ private int eno;
​ private String ename;
​ —----
}

4.​Create a Repository interface:

@Repository
public interface EmployeeRepository extends JpaRepository{

}

5.​create a Runner class:

@Component
public class EmployeeRunner implements ApplicationRunner{
​ public void run(ApplicationArguments args){
​ ​ —----
​ }
}

6.​Execute the Spring Boot application and open the H2 console


with the following url.

http://localhost:1234/h2-console

EX:
application.properties
spring.application.name=app18

server.port=1234
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:durgadb
spring.datasource.username=durga
spring.datasource.password=durga
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.jpa.show-sql=true

Employee.java
package com.durgasoft.app18.beans;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Employee {

@Id
@GeneratedValue
private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}

@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
", eaddr='" + eaddr + '\'' +
'}';
}
}

EmployeeRepository.java
package com.durgasoft.app18.repository;

import com.durgasoft.app18.beans.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends
JpaRepository<Employee, Integer> {
}

EmployeeRunner.java
package com.durgasoft.app18.runner;

import com.durgasoft.app18.beans.Employee;
import com.durgasoft.app18.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class EmployeeRunner implements ApplicationRunner {

@Autowired
private EmployeeRepository employeeRepository;
@Transactional
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("=======Insert Operation=======");
Employee employee = new Employee();
employee.setEname("Durga");
employee.setEsal(50000);
employee.setEaddr("Hyd");
Employee emp = employeeRepository.save(employee);
System.out.println(emp);
System.out.println("Employee Inserted Successfully");
System.out.println();

System.out.println("=======Search Operation======");
Employee emp1 = employeeRepository.findById(1).get();
System.out.println(emp1);
System.out.println();

System.out.println("=======Update Operation======");
emp1.setEname("Ramana");
emp1.setEsal(60000);
emp1.setEaddr("Chennai");
System.out.println("Employee Updated Successfully");
System.out.println();

System.out.println("=======Delete Operation======");
employeeRepository.deleteById(1);
System.out.println("Employee Deleted Successfully");

}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.durgasoft</groupId>
<artifactId>app18</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app18</name>
<description>app18</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

Spring Boot Applications with No SQL Databases[MongoDB]:


—--------------------------------------------------------
MongoDB: It is a No SQL Database, where it is not required to
write SQL queries to perform the Database operations.

MongoDB is a Document Based Database, it is very simple to manage


and develop.

MongoDB contains the number of databases, where the database


contains the number of Collections, where the Collection contains
the number of Documents.

You might also like