Category: Spring boot complete tutorial with example

Home / Category: Spring boot complete tutorial with example

In this article, we learn about spring angularjs integration and how to configure Angular JS routing with spring boot.

As we all know that we use angular js for creating single page application. Routing is the main feature of angular js to create a single page application.

It is very easy to integrate angular js with the spring boot application. And we can use either CDN or Maven dependency to create an angular application.

If you want to learn the integration of angular js with the spring boot application using Maven dependency you can check out this post.

What is Angular Js Routing?

As already told you that using angular js we can create the single page application. And routing allows displaying different page content on a single page.

Suppose when my application runs it will display the content of the index.jsp file. So this is my main page and I want to display diff page content on this page only because we are creating a single page application.

Integrate Angular Js with Spring boot application.

To integrate angular js with spring boot we have to follow the below steps:

  1. Create a spring boot web project with starter web dependency.
  2. Create a WEB-INF folder inside webapp folder. And after that create jsp folder inside the WEB-INF folder.
  3. Create JSP files inside the WEB-INF/jsp folder.
  4. Now create a JS folder for the routing.js file inside the static folder.

spring angularjs
spring angularjs example
spring angularjs example

Till now we have created our Project and create JSP inside our WEB-INF/jsp folder. Now add view prefix and suffix for displaying JSP files in your application. properties file.

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

Now open index.jsp file because when we run our application this file content display. Because we map this file to (“/”) endpoint in our controller class.

We add the angular and angular CDN on this page and also add our routing.js file reference in this file that we create inside the static/JS folder.

index.jsp

angular spring data rest
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring Angular Routing Example</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
 <script src="JS/routing.js"></script>

</head>
<body ng-app="myRoutingApp">
<center><h2>This is a Index Page</h2></center>
<hr>
<ul>
  <li><a href="#!home">HOME</a></li>
  <li><a href="#!contact">CONTACT US</a></li>
  <li><a href="#!signup">SIGN UP</a></li>
</ul>

<hr>
<center><div ng-view></div></center>
</body>
</html>

Note: Make sure your href tag value is the same as that you give for when tag in your routing.js file.

routing.js

angular spring data rest
var app = angular.module("myRoutingApp", ["ngRoute"]);
app.config(function($routeProvider) {
  $routeProvider
  .when("/home", {
    templateUrl : "homeEndPoint"
  })
  .when("/contact", {
    templateUrl : "contactUsEndPoint"
  })
  .when("/signup", {
    templateUrl : "signUpEndPoint"
  })
  .otherwise({
	  templateUrl : "defaultEndPoint"
	  });
});

Note: Make Sure your template Url value is the same as that you define in your controller class endPoint.

MyController.java

package com.vasu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {

	
	@GetMapping("/")
	public String index() {
		return "index";
	}
	
	@GetMapping("/signUpEndPoint")
	public String signUp() {
		return "signup";
	}
	
	@GetMapping("/homeEndPoint")
	public String home() {
		return "home";
	}
	
	@GetMapping("/defaultEndPoint")
	public String defaultRoute() {
		return "default";
	}
	
	@GetMapping("/contactUsEndPoint")
	public String contact() {
		return "contact";
	}
}

Now if you see we use <div ng-view></div> in our index.jsp file this is the place where our routing performs. This means all pages according to routing will display inside this tag.

Now run your application and see output. While after running application our default.jsp page content will display inside <div ng-view></div> tag.

Note: We see by default default.jsp content because we use .otherwise tag inside our routing.jsp file. And no routing is found for “/” so .otherwise template will display.

Download Complete code from Github

You may also like:

Spring boot security using JWT ( JSON WEB TOKENS ).

 How to deploy spring boot application on docker 

Spring Boot With AngularJS Using WebJars

Help Others, Please Share

In this artice we learn how to install github. As we know that Git is an open-source distributed version control software and we use git for versioning our software.

Using git we can upload our code on a central location called git repository. To upload our code on git we require below tools:

  1. A GitHub account
  2. Git installed on your window machine

How to create GitHub account

To create GitHub account you have to follow the below steps:

  1. Go to the GitHub website URL ( open Github ).
  2. Click on SignUp.
  3. Fill the form and click on Create account.
  4. Now you will get an email from GitHub click on the verify link.
How to install github
how to install github on windows
How to install github

How to install github on windows

To install Git on your window system you have to follow the below steps:

  1. Go to the git website using URL ( open git )
  2. Click on download.
  3. Now your download will start.
  4. Go to download folder and open the .exe file.
  5. You have successfully installed the git.
how to install github on windows
github on window
github
github
github

After this click on Next on every window. Do not change the default setting just click on Next on every window.

After completing all steps you will get a window click on Launch Git Bash and after that click on finish.

window github
github on window

Now just check the version of the git using below command.

git --version
github

So congrats till now you have successfully setup both the steps. You have created your account on GitHub and you have also installed git on your window machine.

Till this point we have complete git setup. Now lets see how to upload your file from your computer system to your GitHub repository through the git commands.

Lets see what we are going to do using below steps:

  1. Create a folder on our system.
  2. A .txt file and write some data in that file.
  3. Create a GitHub repository.
  4. Commit our .txt file means give some message to your commit so we can recognizes our version using this message.
  5. Link GitHub repository URL to our folder.
  6. Push our .txt file to the GitHub repository.

To follow above steps you must have some basic knowledge about the below Linux commands.

  1. mkdir
  2. cd
  3. touch
  4. vim

We use mkdir command for creating the folder. In this example we create a folder with name myGitHubFolder.

 mkdir myGitHubFolder

cd command is using for go inside the directory or folder of the given path.

 cd myGitHubFolder/

touch command is using for creating the files. In our case we create a .txt file using this touch command.

touch myGitFile.txt

vim command is using to open the .txt file and use to write some text inside that file.

vim myGitFile.txt

After using the above command a window display. After the press i from your keybord.

i is used for insert. After that write some text in that file and save. For saving data we have to press the below keyword.

esc : wq!

and press enter after typing above keywords.

github
github
github

Till now we have created a Folder with name myGitHubFolder and after that we create a .txt file inside this folder with name myGitFile.txt and put some text inside that.

Now we have to create a GitHub repository and for that we have to Sign in to our GitHub account and create the new repository.

github
how to install github in windows
how to install github in windows
how to install github in windows
how to install github in windows

You have successfully created a GitHub repository and after creating that you will see some commands display on that repository .

git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/vasurajput/JavadreamRepositry.git
git push -u origin main

Now open you git bash terminal and follow the below steps:

  1. Initialize git using git init command
  2. Add your .txt file using git add . command.
how to install github in windows

Now add GitHub user and GitHub repository URL to git bash.

github
github on window
how to install github in windows
github
how to install github in windows
how to install github in windows

You may also like:

Spring boot security using JWT ( JSON WEB TOKENS ).

spring batch example

Help Others, Please Share

Copy constructor in java is used to create the copy of an object.

Is there any copy constructor in java by default?

Java does not create any copy constructor by default like c++, We have to create the copy constructor explicitly.

First look at the complete code of copy constructor than we explain it step by step.

package Practice; 

  class Student { 
	private int id; 
	private String name; 

	public Student(Student copy) { 
		this.id = copy.id; 
		this.name = copy.name; 
	} 

	public Student(int id, String name) { 
		this.id = id; 
		this.name = name; 
	} 

	@Override 
	public String toString() { 
		return "Student [id=" + id + ", name=" + name + "]"; 
	} 
} 

public class CopyConstructor { 
	public static void main(String[] args) { 
		Student s1 = new Student(1, "vasu"); 
		Student s2 = new Student(1, "vishu"); 

		Student s3 = new Student(s1); 

		System.out.println(s1); 
		System.out.println(s2); 
		System.out.println(s3); 
	} 

} 

Now Run this programe and see the output.

Student [id=1, name=vasu] 
Student [id=2, name=vishu] 

Student [id=1, name=vasu] 

Explanation of above code:

To create a Copy constructor we have to define our class constructor like below.

class Student { 
 private int id; 
 private String name; 

public Student(Student copy) { 
      this.id = copy.id; 
      this.name = copy.name; 
  } 
}

In above syntax we define a Student class with two fields

  1. Id
  2. name

And a constructor that accept Student class object. And we assign this Student object value to our instance variable.

Now create a parameterized constructor and override the toString() method to see how the copy constructor works. Now our code looks like below:

class Student { 
	private int id; 
	private String name; 

	public Student(Student copy) { 
		this.id = copy.id; 
		this.name = copy.name; 
	} 

	public Student(int id, String name) { 
		this.id = id; 
		this.name = name; 
	} 

	@Override 
	public String toString() { 
		return "Student [id=" + id + ", name=" + name + "]"; 
	} 
} 

As you can see we have a class named Student with two constructor.

  1. Parameterized constructor
  2. Copy Constructor

Parameterized constructor accept id and name as a parameter and assign them to our instance variable.

Copy Constructor accepts a Student object and assigns them to our instance variable.

Now create the main method and create Object of Student class like below.
public static void main(String[] args) { 
		Student s1 = new Student(1, "vasu"); 
		Student s2 = new Student(1, "vishu"); 

		Student s3 = new Student(s1); 
		System.out.println(s1); 
		System.out.println(s2); 
		System.out.println(s3); 
	} 

As you can see we have define two object of class Student s1 and s2.

Now we create another Student object named s3 and assign object s1 to it.

Now we simply print all three objects.

See the result of the s3 object it is the same as the s1 object. This is because of the copy constructor because we pass this s1 object to our copy constructor using the below line of code.

Student s3 = new Student(s1); 

Copy constructor create the shallow copy not deep copy of objects.

Now you are confused why we use a copy constructor if we create the copy of the object using the clone method.

Copy Constructor Vs Clone method.

  1. It is very easy to create a copy of an object using a copy constructor as compare to the Clone method.
  2. If we use the Clone method then we have to implement the Clonable interface and also need to handle CloneNotSupportedException.

You may also like :

Spring boot security using JWT ( JSON WEB TOKENS ).

Optional in java 8 complete example

Help Others, Please Share

We know that we can easily design APIs in a spring boot application. @PathVariable and @RequestParam are the most used annotations of the spring boot framework. Both Spring PathVariable and Spring RequestParam used to extract parameters from GET requests.

Sometimes we need to pass some values in our URL for processing the business logic. And to extract these values we use @PathVariable and @RequestParam annotation of the spring boot framework.

There are two types of URLs that you have seen when you call any GET request API.

1- http://localhost:8080/getUserByName/vasu

2- http://localhost:8080/getUserByName?name=vasu

See the difference between above two URLs. For example we have to fetch a user record by his name and we have to pass the name of user in the URL. So there are two ways you can pass this name in URL like above.

The difference in above two URL is.

1- In the first URL, we pass the name directly like /vasu this way of passing parameter fetched by the @PathVariable annotation.

2- In the Second URL, we pass a name with a parameter like ?name=vasu this way of passing a parameter fetched by the @RequestParam annotation.

Spring PathVariable and Spring RequestParam both annotations are present in Spring boot you just have to add the starter web dependency in your pom.xml file.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Now create a Controller class and make two endpoints one for @PathVariable and another for @RequestParam.

package com.vasu.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

	@GetMapping("/getUserByName/{name}")
	public String getName(@PathVariable String name) {
		return "Your name using @Pathvariable is " + name;
	}

	@GetMapping("getUserByName")
	public String getNameReqParam(@RequestParam String name) {
		return "Your name using @RequestParam is " + name;
	}
}

Now run you application and check both the endpoints.

Output of @PathVariable endpoint is

spring pathvariable annotation

Output of @RequestParam endpoint is

spring requestparam annotaion

Everything is fine now. But there is a catch just focus on the below points.

1- Make sure the value inside your {} braces and the value you use with @PathVariable must be same otherwise you will get an exception.

For example @GetMapping(“/getUserByName/{name}“) and @PathVariable String name. In this we use same parameter that is name.

Just change the value and run the application for example if your @PathVariable endpoint is like below.

	@GetMapping("/getUserByName/{name1}")
	public String getName(@PathVariable String name) {
		return "Your name using @Pathvariable is " + name;
	}

In the above code, we change the parameter to {name1} and the parameter with @PathVariable is the name. Now run the application and hit the URL you will get an exception like below.

Spring pathvariable

And in console exception like below

[org.springframework.web.bind.MissingPathVariableException: Missing URI template variable 'name' for method parameter of type String]

So if you want to use the different parameter names in both places then you have to use the name attribute of @PathVariable annotation like below.

@GetMapping("/getUserByName/{name1}")
public String getName(@PathVariable(name = "name1") String name) {
return "Your name using @Pathvariable is " + name;
	}

Now run your application the same api will work now.

Do the same change and play with @RequestParam endpoint also and see the differences.

You may also like :

Spring boot security using JWT ( JSON WEB TOKENS ).

spring batch example

Spring boot cache example

Actuator in spring boot for monitoring application

Profiles in Spring boot application

Help Others, Please Share

In this article, we learn about How to parse JSON in java using JsonParser . JsonParser is used to parse the JsonObject and JsonArray.

As a java developer, we always deal with data in JSON or XML format. And sometimes we have to parse this data to perform some business logic.

And sometimes we have to convert the string into a JSON object or JSON array. So for this, we also use this JSON parser in java.

So in this example, we see how to convert a string into JsonObject and how to parse the JSON data using JsonParser.

To use this JsonParser in java application we have to add the below dependency in our pom.xml file.

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Now Just take a programming example. In this example, we make a Post request and send some JSON data. And parse this JSON data using the parser.

Let’s take an example that we are trying to parse the below JsonObject.

{
	"name": "vasu",
	"age": 26,
	"email": "vasu@gmail.com"
}

So to parse the above JsonObject I will make the below logic in my controller class.

package com.javadream.jsonparser.controller;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JsonParserController {

	private static final Logger logger = LoggerFactory.getLogger(JsonParserController.class);

	private JSONParser parser = new JSONParser();

	@PostMapping("/parseSimpleJson")
	public String parser(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();
			
			logger.info("name= "+name + " ,age= "+age + " ,email= "+email);
			return "Your name is "+ name + " and you are " + age + " old. Your email id is" + email ;
 		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}
}

We are using below steps to parse this jsonObject.

  1. We are creating a JSONParser object.
  2. Then receive this JsonObject in String formate in our Post endPoint.
  3. Convert this String payload to JSON object using the parser.
  4. Now we get a JsonObject.
  5. Now we get the object value using a key.

Now Run this application and make a post request with the given data from the postman.

jsonparser

Now take a complex JsonObject example and try to parse that. Suppose I am getting below JsonObject.

{
	"name": "vasu",
	"age": 26,
	"email": "vasu@gmail.com",
	"educationDetail": {
		"college": "GEHU Dehradun",
		"course": "B.Tech",
		"Branch": "CSE"
	}
}

Now we have another JsonObject with the name educationDetail in our main JsoObject. Let’s see how to parse this data.

So to parse this I am creating another post endPoint. See the code to parse this complex object.

	@PostMapping("/parserComplexJson")
	public String parserComplexJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			return "Hi " + name + " you are student of "+ collegeName +" college and your course is "+ course; 
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

Now run this application and make a post request with given JsonObject.

jsonparser java

Now take an example of a hard JsonObject where we have a JsonArray inside our main JsonObject.

{
	"name": "vasu",
	"age": 26,
	"email": "vasu@gmail.com",
	"educationDetail": {
		"college": "GEHU Dehradun",
		"course": "B.Tech",
		"Branch": "CSE"
	},
	"matrixEducation": [{
		"10ClassBoard": "Pass 10 class from UP Board"
	}, {
		"12ClassBoard": "pass 12 class from UP Board"
	}]
}

Now try to parse the above JsonObject. For this, I am creating another post endPoint. Look at the code below.

	@PostMapping("/parserHardJson")
	public String parserHardJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			JSONArray matrixDetail = (JSONArray) jObj.get("matrixEducation");
			
			JSONObject highSchoolObj = (JSONObject)matrixDetail.get(0);
			String highSchoolboard = highSchoolObj.get("10ClassBoard").toString();
			
			JSONObject interSchoolObj = (JSONObject)matrixDetail.get(1);
			String interSchoolboard = interSchoolObj.get("12ClassBoard").toString();
			

			return "Hi " + name + " you 10 board is  " + highSchoolboard + " and for 12 is  " + interSchoolboard;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

Now if you see JsonArray is the same as a simple Array. It also stores data at indexes. So here I have two indexes first index store information for 10ClassBoard. and second, store information for 12ClassBoard.

Now your class look like below with all three methods.

package com.javadream.jsonparser.controller;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JsonParserController {

	private static final Logger logger = LoggerFactory.getLogger(JsonParserController.class);

	private JSONParser parser = new JSONParser();

	@PostMapping("/parseSimpleJson")
	public String parser(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			logger.info("name= " + name + " ,age= " + age + " ,email= " + email);
			return "Your name is " + name + " and you are " + age + " old. Your email id is" + email;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

	@PostMapping("/parserComplexJson")
	public String parserComplexJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			return "Hi " + name + " you are student of " + collegeName + " college and your course is " + course;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

	@PostMapping("/parserHardJson")
	public String parserHardJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			JSONArray matrixDetail = (JSONArray) jObj.get("matrixEducation");
			
			JSONObject highSchoolObj = (JSONObject)matrixDetail.get(0);
			String highSchoolboard = highSchoolObj.get("10ClassBoard").toString();
			
			JSONObject interSchoolObj = (JSONObject)matrixDetail.get(1);
			String interSchoolboard = interSchoolObj.get("12ClassBoard").toString();
			

			return "Hi " + name + " you 10 board is  " + highSchoolboard + " and for 12 is  " + interSchoolboard;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}
}

Now run your application and make a post request with this hard JsonObject data.

jsonparser

Complete Code on Github: JsonParser Example

You may also like:

Spring boot security using JWT ( JSON WEB TOKENS ).

spring batch example

Spring boot cache example

Actuator in spring boot for monitoring application

Profiles in Spring boot application

Help Others, Please Share

In this article, we will learn about MySQL cascade. We use cascading operation when two tables are dependent on each other.

We apply this MySQL cascade on foreign keys. If any data modify from the parent table then this referenced table data will also modify.

The two most important cascade type are:

  1. ON DELETE cascade
  2. ON UPDATE cascade

ON DELETE cascade

We use ON DELETE cascade when we want that all referenced entities will automatically delete if we delete any parent entity.

Take below Example:

Suppose I have Two Tables

  1. person Table
  2. orders Table

person table structure is like below:

create table person(personId bigint(12) primary key,
name varchar(20),
age int(3));

orders table structure is like below :

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE CASCADE );

If you see in orders table we use ON DELETE CASCADE. It means if we delete row from person table than row from orders table automatically delete which have same personId.

Take below Example to understand this

  1. Insert some data in person table.
  2. Insert some data in orders table.
insert into person values(1,"vasu",26);
insert into person values(2,"Ayush",26);
insert into person values(3,"sushmits",25);

insert into orders values(1,"Shoes", 1);
insert into orders values(2,"Jeans", 1);
insert into orders values(3,"Tshirt", 3);
insert into orders values(4,"Jacket",2 );

Now Our person and ordes table will look like this.

On DELETE cascade MySQL cascade

Now try to delete some data from person table.

delete from person where personId=1;

After execute above query check both the tables data and see the difference.

ON UPDATE cascade MySQL cascade

ON UPDATE cascade

This is the same as ON DELETE cascade. The difference is that instead of delete referenced table data it will update the data.

So we follow the same steps as ON DELETE cascade.

  1. Create person table.
  2. Create orders table with ON UPDATE cascade.
  3. Insert data in both the tables.
  4. Now update data from person table.
  5. Now select data from both the tables and see the differnece.

Follow the above steps:

person Table

create table person(personId bigint(12) primary key,
name varchar(20),
age int(3));

2- orders Table

create table orders(orderId bigint(12) primary key, orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON UPDATE CASCADE );

3- Insert Data in both tables.

insert into person values(1,"vasu",26);
insert into person values(2,"Ayush",26);
insert into person values(3,"sushmits",25);
 
insert into orders values(1,"Shoes", 1);
insert into orders values(2,"Jeans", 1);
insert into orders values(3,"Tshirt", 3);
insert into orders values(4,"Jacket",2 );

4- Update persionId from person table.

update person set personId = 4 where personId = 1;

5- Now see the difference by making select query on both the tables.

mysql cascade

There are 5 options for ON DELETE cascade and they are as below.

  1. ON DELETE CASCADE : This is the default cascade as we used in our example.
  2. ON DELETE SET NULL : This cascade is used to set referenced entities value null if we delete the parent table entity.
  3. ON DELETE SET DEFAULT : This cascade is used to set referenced entities value default if we delete the parent table entity.
  4. ON DELETE RESTRICT: we can not delete the row from the parent table if it has any referenced row with the same id.
  5. ON DELETE NO ACTION: In this cascade, there is no referential delete action performed.

To use the above cascade in orders table the structure is like below:

ON DELETE CASCADE

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE CASCADE );

ON DELETE SET NULL

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE SET NULL );

ON DELETE SET DEFAULT

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE SET DEFAULT );

ON DELETE RESTRICT

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE RESTRICT );

ON DELETE NO ACTION

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE RESTRICT );

The same Cascade is also applicable for ON UPDATE cascade just replace DELETE to UPDATE and remain syntax will be same.

You may also like:

MySQL CASE function Example

MySQL Dates and Times

Database backup in MySql

Reference

https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html

Help Others, Please Share

In this post we will see about Optional in Java 8. Optional Class is introduced in Java 8. So before learning about Optional class first we have to know

What is Optional ?

Optional is a container object that is used to contain not-null objects. Optional class introduced in Java 8 to prevent the NullPointerException.

Optional class is present in java.util package.

Just take an example without optional and check if an object contains null or not.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String[] name = new String[5];
		System.out.println(name[3].toUpperCase());
	}
}

If you try to run the above class you will get the below run time exception.

Exception in thread "main" java.lang.NullPointerException
	at com.vasu.myfirstproject.OptionalDemo.main(OptionalDemo.java:9)

We will get the java.lang.NullPointerException at runtime because we have not any value at index 3 and we try to convert this null value in Uppercase. java.lang.NullPointerException is the very comman problem that every java programmer will face.

Now Try the above example again and use Java 8 Optional class to prevent this null pointer exception at run time.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String[] name = new String[5];
		Optional<String> myName = Optional.ofNullable(name[3]);
		if(myName.isPresent()) {
			System.out.println(name[3].toUpperCase());
		}else {
			System.out.println("No value find at the given index");
		}
	}
}

Now if you run the above programe you will get the below output.

No value find at the given index

Now you can see that we use ofNullable() and isPresent() method. This method is the static method of Optional class.

ofNullable() function allowed passed parameter to be null.

isPresent() function returns Boolean. This function return true if any value is present and retun false if null value found.

Optional class provide many static methods and they are:

  1. ofNullable() function allowed passed parameter to be null.
  2. of() function do not allow null value. It will throw NullPointerException if passed parameter is null.
  3. ifPresent() function is execute only if the Optional object is not empty.
  4.  isPresent() function returns Boolean. It return true if value is present otherwise it retun false.
  5. hashCode() function return the hashcode.
  6. get() this function returns the value. Value should be present to use this static function.
  7. orElse() function returns the present value. If value is not present than it will return the default passed value.
  8. orElseGet() function return present value. If value is not present it call other method and return the value.
  9. orElseThrow() function return the value. It will throw Exception if value is not present.

Optional.ofNullable() function Example:

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.ofNullable(name1);
		System.out.println(op1.isPresent());
	}
}

As you can see we have define name1 as null and name2 as vasu. Now try to pass name1 parameter in ofNullable() function and see the output it will return.

false

Now pass the name2 parameter and see the output.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.ofNullable(name2);
		System.out.println(op1.isPresent());
	}
}

Output will be

true

Optional.of() function Example.

This function does not allow null if we try to pass the the null parameter than it will throw run time Exception Just take an example.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.of(name1);
		System.out.println(op1.isPresent());
	}
}

If you run this programe it will throw exception because we pass the null parameter. Output will be

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:221)
	at java.base/java.util.Optional.<init>(Optional.java:107)
	at java.base/java.util.Optional.of(Optional.java:120)
	at com.vasu.myfirstproject.OptionalDemo.main(OptionalDemo.java:10)

Now try to pass not null value as parameter and see the output.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.of(name2);
		System.out.println(op1.isPresent());
	}
}

Output

true

Optional.ifPresent() function Example

This function is execute only if the Optional object is not empty Just look at below example

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		Optional<String> op1 = Optional.empty();
		Optional<String> op2 = Optional.of("My name is vasu");
		
		op1.ifPresent(obj -> System.out.println(obj));
		op2.ifPresent(obj -> System.out.println(obj.toUpperCase()));
	}
}

If you run the above programe you will get the output like

MY NAME IS VASU

This program print op2 object of Optional in Uppercase because op1 object returns the empty Optional object.

Optional.isPresent and Optional.hashCode() Example

Optiona.isPresent() function retuns true if value is presnt and retuns false if value is null. And Optiona.hashCode() function is used to get the hashCode of object.

Look at the below Example

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		String name1 = null;
		String name2 = "vasu";
		
		Optional<String> op1 = Optional.ofNullable(name1);
		Optional<String> op2 = Optional.ofNullable(name2);

		
		System.out.println(op1.isPresent());
		System.out.println(op2.isPresent());
		
		System.out.println(op1.hashCode());
		System.out.println(op2.hashCode());
		
	}
}

Output:
false
true
0
3612237

Optional.get() Example

This function return the present value. For using get() method value should be present.

Just look at below example

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		String name1 = null;
		String name2 = "vasu";
		
		Optional<String> op1 = Optional.ofNullable(name1);
		Optional<String> op2 = Optional.ofNullable(name2);

		
		System.out.println(op1.get());	
	}
}

Now run this program and see the output. Output will be a run time exception because we call get() on null.

Output:

Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.base/java.util.Optional.get(Optional.java:148)
	at com.vasu.myfirstproject.OptionalDemo.main(OptionalDemo.java:16)

Now call get() on op2 object and see the output

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		String name1 = null;
		String name2 = "vasu";
		
		Optional<String> op1 = Optional.ofNullable(name1);
		Optional<String> op2 = Optional.ofNullable(name2);
		
		System.out.println(op2.get());	
	}
}

Output

vasu

Optional.orElse() , Optional.orElseGet() Example

orElse() and orElseGet() function returns the present value. If value is not present than it will return the default passed value.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		Optional<String> op1 = Optional.ofNullable("vasu");
		Optional<String> op2 = Optional.empty();
		
		System.out.println(op1.orElse(new String("vishu")));	
		System.out.println(op2.orElse(new String("vishu")));

	}
}

Output

vasu
vishu

You may also like:

Spring Boot Project Using Spring Initializer

Create WAR of Spring Boot Project

Change Running Server Port in Spring Boot

Spring Boot With MySql

How to use multiple database in a single spring boot application

Reference:


Optional (Java Platform SE 8 ) – Oracle Help Center

Help Others, Please Share

In this post we will see about spring batch. So the first question will come in our mind is

What is Spring Boot Batch ?

Spring boot batch is framework that is designed to execute large and robust batch application.

Batch application Example.

As we know we use spring boot batch to execute large task. So here are some application scenario where we use Batch framework.

1- Suppose we have a big CSV file which contains billions rerecords and i want to store that data in the MySQL database.

So if you try yo insert this billions record in one go your application takes a very very long time to execute this task.

And it may also be possible that your database not support this huge amount of insertion.

So in this case we will use Spring boot Batch framework and execute this task in batch chunks means we divide this task of insertion in chunks.

The above scenario we will cover in another application first we see some easy example to learn spring boot batch framework.

In this example we take a list of names and try to process this list data in batch.

Project Structure:

spring batch

There are some keyword in spring boot batch framework. That we use to process our application.

  1. ItemReader
  2. ItemProcessor
  3. ItemWriter
  4. Step
  5. Job
  6. Job Listener
  7. JobBuilderFactory
  8. StepBuilderFactory
  9. JobLauncher
ItemReader :

ItemReader is like entry point it will read your data from file or from the source you define.

ItemProcessor :

ItemProcessor is process the data that you read using ItemReader.

For Example you read a List of names using ItemReader and you want to convert this name in uppercase. So this task is done by ItemProcessor.

ItemWriter :

After Process the data by ItemProcessor we have to write this data. So for this we use ItemWriter.

Step :

After process all above steps ItemReader, ItemProcessor, ItemWriter we will get the steps.

Job :

Now we have to create a Job that executes the Step. Job is an interface and resides in org.springframework.batch.core package.

Job Listener :

This class deines two methods beforeJob and afterJob. As the name suggest this function is used to perform task before and after job execution.

JobBuilderFactory :

JobBuilderFactory is a class that used to create the Job.

StepBuilderFactory :

StepBuilderFactory is a class that used to create the Step.

JobLauncher :

Till now we have create the Job. Now we have to excute this Job for this we will use JobLauncher.

Now Lets do a coding example. We Just create a List of names and print this List name in batch.

To create above Project we have to follow below steps:

1- Add required dependency in your pom.xml file or add from Maven Repositry.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-batch</artifactId>
</dependency>

2- Now create a class that implements ItemReader interface.

package com.vasu.springbatch;

import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;

public class Reader implements ItemReader<String> {

	private String[] names = {"Vasu","Vishu", "Ayush","Sushmita","konika"};
	private int count;
	
	@Override
	public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
		System.out.println("Inside Read Method");
		if(count < names.length) {
			return names[count++];
		}else {
			count = 0;
		}
		return null;
	}

}

3- Create a class that process above list and convert List names into UpperCase.

package com.vasu.springbatch;

import org.springframework.batch.item.ItemProcessor;

public class Processor implements ItemProcessor<String, String> {

	@Override
	public String process(String item) throws Exception {
		System.out.println("Inside Process method");
		return "PROCESSED "+ item.toUpperCase();
	}
}

4- Create Writer class that implement ItemWriter.

package com.vasu.springbatch;

import java.util.List;

import org.springframework.batch.item.ItemWriter;

public class Writer implements ItemWriter<String> {

	@Override
	public void write(List<? extends String> items) throws Exception {
		System.out.println("Inside Write method");
		System.out.println("Data In UpperCase is " + items);
	}
}

5- Create a Job Listener class .

package com.vasu.springbatch;

import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;

public class MyJobListener implements JobExecutionListener {

	@Override
	public void beforeJob(JobExecution jobExecution) {
		System.out.println("Before Job Started");
	}

	@Override
	public void afterJob(JobExecution jobExecution) {
		System.out.println("After Job Ended " + jobExecution.getStatus().toString());
	}
}

6- Now Create a Config class and initialize all the above beans.

package com.vasu.springbatch;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BatchConfig {
	
	@Autowired
	private StepBuilderFactory sdf;
	
	@Autowired
	private JobBuilderFactory jbf;
	
	@Bean
	public Job job() {
		return jbf.get("myFirstBatchJob") 	
				.incrementer(new RunIdIncrementer())
				.listener(listener())
				.start(step())
				.build();
	}
	
	@Bean
	public Step step() {
		return sdf.get("myFirstBatchStep")
				.<String,String>chunk(3)
				.reader(reader())
				.processor(processor())
				.writer(writer())
				.build();
		
	}

	@Bean
	public Reader reader() {
		return new Reader();
	}

	@Bean
	public Writer writer() {
		return new Writer();
	}

	@Bean
	public Processor processor() {
		return new Processor();
	}

	@Bean
	public MyJobListener listener() {
		return new MyJobListener();
	}
}

7- Use @EnableBatchProcessing annotation in your main class.

package com.vasu.springbatch;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableBatchProcessing
public class SpringbatchApplication {

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

8- Create a Test Class to test the batch process. In this class autowired JobLauncher.

package com.vasu.springbatch;

import org.junit.jupiter.api.Test;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbatchApplicationTests {

	@Autowired
	JobLauncher launcher;

	@Autowired
	Job job;

	@Test
	void testBatch() throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
		JobParameters jobParameters = new JobParametersBuilder()
				.addLong("todayTime", System.currentTimeMillis())
				.toJobParameters();
		launcher.run(job, jobParameters);
	}

}

Now run this class as JUnit Test.

Output:

spring batch

Complete code on Github- Spring batch Github

You may also like

Spring boot security using JWT ( JSON WEB TOKENS ).

HTTPS in Spring Boot

Spring Boot with Apache kafka.

Profiles in Spring boot application

Help Others, Please Share

We know that spring boot framework is an advance framework developed by the pivotal. Using Spring boot we can setup the spring boot hello world example application within 5 minutes.

If we talk about spring framework than this framework will take a very long time to setup the project. We have to define many xml for a tiny task. Using Spring boot we get rid of this and create our project within minutes.

So here we go now it’s time to create the spring boot hello world example. In this Project we just print the Hello Word on our Google Chrome web browser.

To create Spring Boot Hello World project we have to follow the below steps:

  1. First go to the Spring initializr website https://start.spring.io/
  2. Configure Project Metadata configuration
  3. Choose Spring Web dependency from Add Dependency tab.
  4. Click on GENERATE button now you will get a .zip file.
  5. Open your eclipse or any other editor and import this project.
  6. Now make a simple controller class using some spring boot annotation that return simple hello word while calling your end point.

Now follow above steps one by one

1- First we have to go to the spring initializer and here we select Project as Maven Project and Language as Java. Now choose Spring boot version currently we are using 2.3.3.

Now configure the Project Metadata details here you see many options and they are:

Group – It is your package name define so define accordingly here i am define com.vasu

Artifact and Name – Both are same after defining this you will get your complete pacakge like i am defining here myfirstproject. So my package name now become com.vasu.myfirstproject.

Description – Give description about your project.

Package name – It is the combination of Group and Artifact. It will autofill automatically.

Now define your Packaging type here we choose Jar.

Now choose your Java version minimum version is Java 8 for using Spring Boot.

spring boot hello world example
spring boot hello world example
spring boot hello world example

After clicking on GENERATE button you will get your project in .zip format. Now extract this project and open in your eclipse or any other editor.

Now In Your Eclipse Project Structure is like :

spring boot hello world example

your MyfirstprojectApplication.java class is using the annotaion @SpringBootApplication that defines it is you main class you have to run this class to start your project.

Now it’s time to return Hello Word from our application to Chrome Console. So for that create a controller class. We are creating with name MyFirstController.java class.

Here In this class we define two annotaions

  1. @RestController
  2. @GetMapping

@RestController annotation is used to define that our class return object as output we can return any object in this case we simply return the String Object.

@GetMapping annotaion is used to define end point here we define (“/) means if we hit http://localhost:8080 on our browser than we will get the output:

MyFirstController.java
package com.vasu.myfirstproject.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyFirstController {

	@GetMapping("/")
	public String test() {
		return "Hello Word";
	}
}

Application Run Steps:

Right click on MyfirstprojectApplication.java class. Click on Run As now click on Java Application. congrats your application is start now.

Now run your application and hit http://localhost:8080 URL you will get “Hello Word” as output.

spring boot hello world example

Complete code on Github- Spring Boot Hello Word GitHub URL

You may also like:

Create WAR of Spring Boot Project

How to use H2 database in spring boot application

Help Others, Please Share

In this post we will see spring boot https. We Know that our data is going through the network. And if we are using http then our data is visible and anybody can see or intercept this data without any difficulty. spring boot https allows us to encrypt our data over the network so nobody can see our data over the network while transmitting.

For enable HTTPS we follow the below steps.

  1. Go to the bin folder of your JRE installed location and create a certificate using the following command.

Syntax :

keytool -genkey -keystore 
{ GIVE YOUR LOCATION } /{GIVE ANY NAME}.jks
alias tomcat -keyalg RSA -keysize 4096

Example

keytool -genkey -keystore
/usr/local/vasuCertificate.jks 
alias tomcat -keyalg RSA -keysize 4096
2- Copy this certificate inside your resources folder of Project.
3- Make following entry in your application.properties.
# for https
server.port=8442
server.ssl.key-store=classpath:vasuCertificate.jks
server.ssl.key-store-password=vasurajput
server.ssl.key-password=vasurajput
4- Now Make A Controller Class to create some end point.
@RestController
public class HomeController {

private static final Logger logger = LoggerFactory.getLogger("HomeController.class");

  @GetMapping("/")
   public String test() {
    logger.info("Test Controller Call");
     return "index";
   }
}
5- Now create a configuration class for enable HTTPS.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.vasu.HttpsDemo.Controller;

import java.io.File;
import java.io.IOException;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

/**
*
* @author vasu rajput
*/

@Configuration
public class Https {

@Bean
public ServletWebServerFactory servletContainer() {

TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {

@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
  }
};
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
 }

private Connector createStandardConnector() {

Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
  }
}

As we know for https we define 8443 port. So in above configuration class code we define connector.setRedirectPort(8443) this port.

Now if you follow all above steps so you have successfully confgured the https in spring boot.

Now go to your browser and type http://localhost:8080 you will automatically redirect to https://localhost:8443/ port which uses https.

You may also like:

Let’s Encrypt Certificate in Java with Apache Tomcat

Spring Boot Security With JWT and MySQL

Help Others, Please Share

x