Spring Boot
Spring Boot
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]
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.
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.
1.Gson
2.Jackson
3.JSON-B
Spring Boot uses Jacson as the predefined and default
implementation internally.
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,....
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.
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.
“Spring-boot-starter-web”
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.
1.@Configuration
2.@ComponentScan
3.@EnableAutoConfiguration
spring-boot-starter-actuator
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
EX:
App04Application.java
package com.durgasoft.app04;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App04Application {
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>
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 {
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 {
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 {
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.
To get all the option arguments names we will use the following
method.
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 {
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 {
WishRunner.....
WelcomeRunner.....
HelloRunner.....
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 {
server.port=1234
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 {
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 {
EX:
application.properties
server.port=1234
spring.application.name=DemoApp
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 {
spring.banner.location=classpath:fileName.txt
@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;
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 {
Employee Details
-------------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000.0
Employee Address : Hyd
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;
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 {
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 {
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 {
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
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
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 {
@PropertySource(“classpath: filename.properties”)
EX:
@PropertySourrce(“classpath: abc.properties”)
@PropertySourrce(“classpath: ./config/xyz.properties”)
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 {
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 {
Inside the Yaml file, we are able to provide the data in the form
of Key-Value pairs with the indentation operator or levels.
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;
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;
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;
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;
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 {
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 {
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
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 {
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
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 {
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
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;
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 {
User Details
------------------
User Name : nagoorn
User Address : Hyderabad
User Qualifications : BTech MTech PHD
User Technologies : JAVA PYTHON DEVOPS
propertyName:
- Val1
- Val2
- val3
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;
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 {
App12Application.java
package com.durgasoft.app12;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App12Application {
User Details
------------------
User Name : nagoorn
User Address : Hyderabad
User Qualifications : BTech MTech PHD
User Technologies : JAVA PYTHON DEVOPS
Development
Testing
Production
—---
—---
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;
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.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;
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 {
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;
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 {
SpringApplication.run(App13Application.class, 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;
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());
}*/
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;
EmployeeService.java
package com.durgasoft.app12.service;
import com.durgasoft.app12.beans.Employee;
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;
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 {
@Table(name=”emp2”)
public class Employee{
@Id
private int eno;
—---
—---
}
@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){
—----
}
—-----
@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;
@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;
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;
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);*/
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 ;
<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.
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;
@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 {
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);*/
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;
EmployeeService.java
package com.durgasoft.app12.service;
import com.durgasoft.app12.beans.Employee;
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;
@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;
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 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.
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.
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;
@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;
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;*/
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);
}
}
}
<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>
EX:
EntityManagerFactory factory =
Persistence.createEntityManagerFactory(“mysql”);
EX:
EntityManager entityManager = factory.createEntityManager();
EX:
EntityTransaction entityTransaction =
entityManager.createEntityTransaction();
EX:
Employee.java
package com.durgasoft.beans;
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;
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.
@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;
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;
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>
1.Spring-orm
2.Hibernate-core
3.mysql-connector
@Repository
public ProductDaoImpl implements ProductDao{
@PersistenceContext
private EntityManager entityManager;
<hibernate-mapping>
<class name=”com.durgasoft.beans.Product” table=”product”>
<id name=”pid”/>
<property name=”pname”/>
<property name=”pcost”/>
</class>
</hibernate-mapping>
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:
EX:
Employee.java
package com.durgasoft.beans;
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;
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;
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 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.
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.
@Repository
public interface EmployeeRepository extends
JpaRepository<Employee, int>{
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;
—---
}
@Repository
public ProductRepository extends JpaRepository<Product,
int>{
}
@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:
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;
}
}
@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;
@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);*/
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;
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>
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.
If we want to get all Results from the Page object to the List
object 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;
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 {
App17Application.java
package com.durgasoft.app17;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App17Application {
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.
Spring Boot data JPA supports the In Memory Databases like H2,
Derby,...
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
@Entity
public class Employee{
@Id
@GeneratedValue
private int eno;
private String ename;
—----
}
@Repository
public interface EmployeeRepository extends JpaRepository{
}
@Component
public class EmployeeRunner implements ApplicationRunner{
public void run(ApplicationArguments args){
—----
}
}
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;
@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>