Category: Spring boot complete tutorial with example

Home / Category: Spring boot complete tutorial with example

As we all know MongoDB is a No SQL database, springboot provides a MongoTemplate object to perform MongoDB operations. We just have to autowired this object in our service class. In this example we will see how to perform MongoDB CRUD operations in SpringBoot with MongoTemplate.

For performing MongoDB queries operations in springboot we have to follow some steps:

1- create a springboot project and add the following dependencies in your pom.xml file.

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

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

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
 </dependency>

2- After adding dependency in pom.xml file go to application.properties file and add following lines.

spring.data.mongodb.database=vasuMongoDB
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

3- create a service class and autowired the object of MongoTemplate class.

@Autowired
 private MongoTemplate template;

4- perform database crud operation using this template object .

We are creating a mongoDb crud application for user data. you can see the complete code on Github

SAVE Data:

@Override
public JSONObject save(JSONObject payload) {
        try {
            Document condition = new Document();
            String fName = payload.get(Collections.userCollection.FIRST_NAME).toString();
            String lName = payload.get(Collections.userCollection.LAST_NAME).toString();
            String email = payload.get(Collections.userCollection.EMAIl).toString();
            condition.clear();
            condition.append(Collections.userCollection.FIRST_NAME, fName)
                    .append(Collections.userCollection.LAST_NAME, lName)
                    .append(Collections.userCollection.EMAIl, email);

            
            MongoCollection<Document> collection = template.getCollection(Collections.userCollection.COLLECTION_NAME);
            collection.insertOne(condition);
            Object getInsertId = condition.get("_id");
            logger.info("vvv::  insertId= " + getInsertId);
            if (getInsertId.toString().equals("")) {
                return responses.getResponse(responses.ERROR);
            }
            return responses.getResponse(responses.OK);
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

Find All Data:

  public Object getAll() {
        try {
            condition.clear();
            condition.append(Collections.userCollection.EMAIl, new Document("$ne", ""));
            Object findAll = find(condition, Collections.userCollection.COLLECTION_NAME);
            return findAll;
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

FindBy id:

 public Object find(Document condition, String collectionName) {
        try {
            FindIterable<Document> find = template.getCollection(collectionName).find(condition);
            MongoCursor<Document> iterator = find.iterator();
            Document docsResponse = new Document();
            JSONArray responseArr = new JSONArray();
            while (iterator.hasNext()) {
                responseArr.add((JSONObject) parser.parse(iterator.next().toJson().trim()));
            }
            if (responseArr.size() > 0) {
                return responseArr;
            }
            return null;
        } catch (Exception e) {
            logger.error(e, e);
            return null;
        }
    }

Delete Data:

      public JSONObject delete(Document condition, String collectionName) {
        try {
            Document findOneAndDeleteResponse = template.getCollection(collectionName).findOneAndDelete(condition);
            return responses.getResponse(responses.OK);
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

Update Data:

public JSONObject update(JSONObject whereObj, JSONObject updateObj, String collectionName) {
        try {
            logger.info("vvv::  whereObj= " + whereObj + ", updateObj= " + updateObj + ", collName= " + collectionName);
            if (whereObj == null || updateObj == null || collectionName == null) {
                logger.info("vvv::  insufficentData");
                return responses.getResponse(responses.INSUFFICIENT_DATA);
            }
            Query query = new Query();
            Update update = new Update();

            //iterate where Condition
            Set keySet = whereObj.keySet();
            Iterator iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                query.addCriteria(Criteria.where(key).is(whereObj.get(key)));
            }

            //iterate Update Value
            Set updateSet = updateObj.keySet();
            Iterator updateItr = updateSet.iterator();
            while (updateItr.hasNext()) {
                String key = (String) updateItr.next();
                update.set(key, updateObj.get(key));
            }
            logger.info("vvv::  query= " + query.toString());
            logger.info("vvv::  update= " + update.toString());
            UpdateResult updateMulti = template.updateMulti(query, update, collectionName);
            logger.info("vvv::  updateMulti= " + updateMulti);
            if (updateMulti.getModifiedCount() == 1) {
                return responses.getResponse(responses.OK);
            }
            return responses.getResponse(responses.ERROR);
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

Find Complete Code on Github

https://github.com/vasurajput/JavaDream/tree/master/SpringBootMongoDB
Help Others, Please Share

AngularJs has widely used technology nowadays which is introduced by GOOGLE and it is mainly used for single page application. To integrate AngularJs with SpringBoot is very simple we can integrate AngularJs with CDN also but in this, I will show you how to integrate AngularJS using webjars in spring boot. We have to follow some steps to integrate AngularJS with SpringBoot and Steps are:

Steps to follow:

  1. Add AngularJs webJar in your pom.xml file
  2. create a javascript file inside your static folder
  3. link webjar and javascript file in your JSP page
  4. Create a Controller class for display your JSP page

Project Directory Structure:

1- Angular WebJar :

<dependency>             
<groupId>org.webjars</groupId>
<artifactId>angularjs</artifactId>
<version>1.7.0</version>
</dependency>

2- main.js

var app=angular.module('myapp',[]);
app.controller('myctrl',function($scope){
$scope.firstname="vasu Rajput";
});

3- index.jsp

<html ng-app="myapp">
<body ng-controller="myctrl">
    <h1>Hi You are a Nice Guy {{firstname}}</h1>
    <p>Angular Example 2 way Binding</p>
    <input type="text" ng-model="tyeMe"><br>
    <h4>{{tyeMe}}</h4>
    <script src="webjars/angularjs/1.7.0/angular.js"></script>
    <script src="JS/main.js"></script>
</body>
</html>

4- MyController.java

@Controller
public class MyController {
@GetMapping("/")
public String index() {
return "index";
}
}

Now run your programe you will see output like:

Help Others, Please Share

Sending email is a very basic task in every applications. Spring boot provides JavaMailSender interface that is used for sending Simple text as well as HTML email to end user. So for sending email in spring boot we have to follow some steps and steps are:

  1. Create a spring boot projects using spring initializer with Mail dependency.
  2. Write your email properties in application.properties file.
  3. Create a Controller class and make a POST end point to receive email id.
  4. Create a Service class for sending email to given email id.
  5. we will send both simple text as well as HTML email to given email id.

Project Directory Strucuture

2- Write your email properties in application.properties file.

 spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=vasu@gmail.com
spring.mail.password= Write Your Gmail Account Password
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000

3- Create a Controller class and make a POST end point to receive email id

 @RestController
public class MyController {

@Autowired
private MyService service;

@PostMapping("/sendMail")
public ResponseEntity sendEmail(@RequestParam String emailId) {

ResponseEntity sendResult = service.send(emailId);
return sendResult;
}
}

4- Create a Service class for sending email to given email id.

First We Send a Simple plain Text Message to given Email Id

 @Service
public class MyService {

@Autowired
JavaMailSender mailSender;

public ResponseEntity<?> send(String emailId) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message);
messageHelper.setTo(emailId);
messageHelper.setSubject("Testing");
messageHelper.setText("Nice Try");
mailSender.send(message);
System.out.println("succesfully SendEmail");
return new ResponseEntity<Object>("succesfully SendEmail",HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<Object>("Error in sending Mail", HttpStatus.INTERNAL_SERVER_ERROR);
}
}

Now Send a HTML message to given email id. For sending HTML email just write your message in HTML formate and set setText boolean flag to true


Eg:
StringBuilder builder = new StringBuilder();
builder.append("<html><h3>Email in HTML</h3></html>");
messageHelper.setText(builder.toString(), true);

@Service
public class MyService {
@Autowired
JavaMailSender mailSender;

public ResponseEntity<?> send(String emailId) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message);
StringBuilder builder = new StringBuilder();
builder.append("<html><h3>Email in HTML</h3></html>");
messageHelper.setTo(emailId);
messageHelper.setSubject("Testing");
messageHelper.setText(builder.toString(), true);
mailSender.send(message);
System.out.println("succesfully SendEmail");
return new ResponseEntity<Object>("succesfully SendEmail", HttpStatus.OK);
}catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<Object>("Error in sending Mail", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}




Help Others, Please Share

Configure your application with database is the basic need of every project. Spring Boot provides JPA (java Persistance API) to Connect to MySQL database. For connecting our Spring Boot application we have to follow some basic steps, and steps are:

  1. Create a Spring Boot Project with MySQL and JPA dependency
  2. Configure MySql properties in application.properties file
  3. create a Model Class
  4. Create a interface repository that extends JpaRepository interface
  5. Create a Controller Class
  6. Create a Service Class for business logic.
  7. Create a Response Class For Display Custom Responses.

2- Configure MySql properties in application.properties file

 spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/vasu
spring.datasource.username=root
spring.datasource.password=12345@
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
hibernate.hbm2ddl.auto=create-drop
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardI mpl

3- Create a Model Class, We are creating a Model Class With Name Student

 @Entity
@Table(name = "Student")
public class StudentModel implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Id", nullable = false)
private Long id;

@Column(name = "Name", nullable = false)
private String name;

@Column(name = "Age", nullable = false)
private int age;

@Column(name = "Email", nullable = false, unique = true)
private String email;

//Constructor
//Getter-Setter

4- Create a interface repository that extends JpaRepository interface

 @Repository
public interface StudentRepositry extends JpaRepository {
}

5- Create a Controller Class

 @RestController
public class StudentController {

@Autowired
private StudentService service;

@GetMapping("/")
public ResponseEntity getAll() {
ResponseEntity get = service.get();
return get;
}

@GetMapping("/getById/{id}")
public ResponseEntity getById(@PathVariable("id") Long Id) {
ResponseEntity byId = service.getById(Id);
return byId;
}

@PostMapping("/update")
public ResponseEntity update(@RequestParam Long id,
@RequestParam String name,
@RequestParam String email,
@RequestParam int age) {
ResponseEntity update = service.update(id, new StudentModel(name, age, email));
return update;
}

@GetMapping("/delete/{id}")
public ResponseEntity delete(@PathVariable("id") Long id) {
ResponseEntity delete = service.delete(id);
return delete;
}

@PostMapping("/insert")
public ResponseEntity insert(@RequestParam String name,
@RequestParam String email,
@RequestParam int age) {

ResponseEntity save = service.save(new StudentModel(name, age, email));
return save;
}

6- Create a Service Class for business logic

@Service
public class StudentService {
private static final Logger logger = LoggerFactory.getLogger(StudentService.class.getName());

@Autowired
private StudentRepositry dao;
@Autowired
private Responses response;

public ResponseEntity save(StudentModel student) {
try {
StudentModel save = dao.save(student);
return new ResponseEntity(save, HttpStatus.OK);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}


public ResponseEntity get() {
try {
List findAll = dao.findAll();
return new ResponseEntity(findAll, HttpStatus.OK);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

public ResponseEntity update(Long id, StudentModel student) {
try {
Optional findById = dao.findById(id);
if (findById.isPresent()) {
StudentModel get = findById.get();
get.setAge(student.getAge());
get.setEmail(student.getEmail());
get.setName(student.getName());
StudentModel save = dao.save(get);
return new ResponseEntity(save, HttpStatus.OK);
}
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}


public ResponseEntity delete(Long id) {
try {
dao.deleteById(id);
return new ResponseEntity(response.getResponse(response.OK), HttpStatus.OK);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}


public ResponseEntity getById(Long id) {
try {
Optional findById = dao.findById(id);
if (findById.isPresent()) {
StudentModel get = findById.get();
return new ResponseEntity<Object>(get, HttpStatus.OK); }
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

7- Create a Response Class For Display Custom Responses.

/*
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.
*/

@Component
public class Responses {
private static final Logger logger = LoggerFactory.getLogger(Responses.class.getName());

public static final int OK = 0;
public static final int ERROR = 1;
public static final int INSUFFICIENT_DATA = 3;
public static final int INVALID_USER = 4;
public static final int UNKNOWN = 501;

public static JSONObject getResponse(int code) {
logger.info("vvv:: responseCode= " + code);
JSONObject response = new JSONObject();
switch (code) {
case OK:
response.put("code", OK);
response.put("message", "OK");
break;
case ERROR:
response.put("code", ERROR);
response.put("message", "Internal Error");
break;
case INSUFFICIENT_DATA:
response.put("code", INSUFFICIENT_DATA);
response.put("message", "Insufficient Data");
break;
case INVALID_USER:
response.put("code", INVALID_USER);
response.put("message", "Invalid User");
break;
default:
response.put("code", UNKNOWN);
response.put("message", "Unknown Response code");
}
logger.info("vvv:: MakeResponse= " + response); return response;
}
}

OUTPUT

Help Others, Please Share

We know that when we create a Spring Boot project it will make a JAR file after compilation. But some developers prefers WAR over JAR for deploying their application on tomcat server. so for converting JAR into WAR in Spring Boot application we have to follow some rules and the rules are:

  1. Add spring-boot-starter-tomcat dependency into pom.xml file.
  2. change packaging to war instead of jar in pom.xml file.
  3. Go to your Spring Boot main class and extends SpringBootServletInitializer abstract class.
  4. Override the SpringApplicationBuilder method of
    SpringBootServletInitializer abstract class .
  5. Now just clean and build your project you will get your war file inside target folder of your project.

1- Add below dependency to pom.xml

<dependency> 
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>

2- Change packaging to war instead of jar in pom.xml file

<packaging>war</packaging> 

3- Go to main class and extends SpringBootServletInitializer abstract class.

@SpringBootApplication
public class SpringBootWarExampleApplication extends SpringBootServletInitializer{

4- Override the SpringApplicationBuilder method of
SpringBootServletInitializer abstract class

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder app) {
return app.sources(SpringBootWarExampleApplication.class);
}

Now Your Main Class will look like this

package com.vasu.SpringBootWarExample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class SpringBootWarExampleApplication extends SpringBootServletInitializer{

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder app) {
return app.sources(SpringBootWarExampleApplication.class);
}

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

5- Now just clean and build your project you will get your war file inside target folder of your project.

You may also like

Change Default Banner Spring Boot

How to read property values in spring boot application

How to use H2 database in spring boot application

Spring Boot With MySql

Profiles in Spring boot application

spring batch example

Help Others, Please Share

In this post we will learn about spring boot banner. As we know when we run our application we see the default spring banner.

Suppose i want to change this spring boot banner text and want to print my name when i run the spring boot application.

So to change the default banner text we have to follow given steps:

  1. Create a Text file with name banner.txt inside resource folder of your project.
  2. There are some online websites where you can write your own custom banner you can follow the below link to generate your custom banner.
  3. https://devops.datenkollektiv.de/banner.txt/index.html
  4. Now just simply clean and build your project .
  5. Now Run your project you will see your custom banner instead of default banner

spring boot banner
spring boot banner generator

You may also like:

How to read property values in spring boot application

How to use H2 database in spring boot application

JSP with Spring Boot

spring batch example

Profiles in Spring boot application

Help Others, Please Share

x