JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Working with SQL Databases and Spring Boot

August 21, 2015 by Mohamed Sanaulla Leave a Comment

In this tutorial I am going to explain your how to use SQL Databases and Spring Boot together. If you are working in a  Spring Framework projects, you should know very well about how to use  SQL databases and Spring Boot for persisting application data.

SQL Databases are an integral part of any application being development. They help in persisting application data. SQL Databases provide advanced support for querying data using the Structured Query Language(SQL). Spring Boot provides great support for interacting with SQL databases with minimal or no XML configurations. In this article we will look at the following:

  1. Configuring in memory database and fetching data using JdbcTemplate
  2. Configuring production database and fetching data using JdbcTemplate
  3. Using JPA and Spring Data

In Memory Database Using JdbcTemplate

The fastest way to test something is to make use of embedded db. This helps in getting started with the application without much hassles of installing the db. Let us see how we can use embedded db and also how we can initialize the schema we need to be created in the embedded db. First let us add the dependencies to pom.xml:

  • Read : Apache Maven for Beginners

[code lang=”xml”]
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
[/code]

  • In the above dependencies we have included the JDBC dependency – this gives us JdbcTemplate and other JDBC libraries, the org.hsqldb dependency adds embedded hsqldb.
  • We need not add any configurations to connect to this embedded db, its all managed by Springboot.
  • These embedded DBs are in-memory and each time the application shuts down the schema and data gets erased. One way to keep schema and data in the in-memory is to populate it during application startup. This is taken care by Springboot.
  • One of the approaches is to create schema.sql and data.sql files in the application classpath.
  • Spring JDBC uses these sql files to create schema and populate data into the schema. There are other techniques which are listed here.

One can create mulptiple schema.sql and data.sql files, one for each db platform. So we can have schema-hsqldb.sql, data-hsqldb.sql, schema-mysql.sql and so on. And the file to be picked is decided by the value assigned to the property spring.datasource.platform. In this post we are going to create a schema-hsqldb.sql file with the following contents:

[code lang=”sql”]
CREATE TABLE person(
first_name VARCHAR(150),
last_name VARCHAR(150),
age INTEGER,
place VARCHAR(100)
);
[/code]

Next is to create application-local.properties file to define the values for application properties. Please read our previous articles about external configurations. Below is the contents for application-local.properties:

[code]
spring.datasource.platform=hsqldb
[/code]

Next is to create the Person model class:

[code lang=”java”]
package net.javabeat;

public class Person {
private String firstName;
private String lastName;
private int age;
private String place;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}

public String toString(){
StringBuilder builder = new StringBuilder();
builder.append(this.getFirstName())
.append(", ")
.append(this.getLastName())
.append(", ")
.append(this.getPlace())
.append(", ")
.append(this.getAge());

return builder.toString();
}

}
[/code]

Next is to create a service class PersonService which makes use of JdbcTemplate to insert data and retrieve data from hsqldb. There are two method in the service class- addPerson and getAllPerson. addPerson adds a new row to the person table and getAllPerson fetches all the rows in the person table. Below is the PersonService class definition:

[code lang=”java”]
package net.javabeat;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

@Service
public class PersonService {

@Autowired
private JdbcTemplate jdbcTemplate;

public int addPerson(Person person){
String sql = "INSERT INTO person(first_name, last_name, age, place) VALUES(?,?,?,?)";
return jdbcTemplate.update(sql, person.getFirstName(),
person.getLastName(), person.getAge(), person.getPlace());
}

public List<Person> getAllPerson(){
return jdbcTemplate.query("SELECT * FROM person", new RowMapper<Person>(){

public Person mapRow(ResultSet rs, int arg1) throws SQLException {
Person p = new Person();
p.setAge(rs.getInt("age"));
p.setFirstName(rs.getString("first_name"));
p.setLastName(rs.getString("last_name"));
p.setPlace(rs.getString("place"));
return p;
}

});
}
}
[/code]

Creation of DataSource instance, JdbcTemplate instance is all taken care by Spring Boot. Next is creation of the main class which launches the SpringApplication. Below is the definition of SpringbootSqlDemo class:

[code lang=”java”]
package net.javabeat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootSqlDemo implements CommandLineRunner{

Logger logger = LoggerFactory.getLogger(SpringbootSqlDemo.class);

@Autowired
PersonService personService;

public void run(String… args) {
Person person = new Person();
person.setFirstName("FName");
person.setLastName("LName");
person.setAge(20);
person.setPlace("Place");

if ( personService.addPerson(person) > 0){
logger.info("Person saved successfully");
}

for(Person p : personService.getAllPerson()){
logger.info(p.toString());
}

}

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

}
[/code]

The above class implements CommandLineRunner interface so that it can run once the Spring Boot application context has been completely initialized. This allows for creation of instances of DataSource, JdbcTemplate, PersonService and other beans.

The run(String... args) method first inserts one row into the person table and then retrieves all the rows in the person table and logs them using the logger. So once we run the application we will be able to see the rows inserted. With all these new files the project structure looks like:
Spring Boot SQL Databases

Let us run the application using the command: mvn spring-boot:run -Dspring.profiles.active=local. Below is the output snippet obtained after the application executes:

[code]
…
2015-08-20 19:50:00.704 INFO 5572 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : Person saved successfully
2015-08-20 19:50:00.719 INFO 5572 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
…
[/code]

You can notice that a new row has been added to person table and also all the rows available in the table have been printed.

Production Database Configurations Using JdbcTemplate

In-memory databases have lot of restriction and are useful in the early stages of the application and that too in local environments. As the application development progresses we would need data to be present even after application ends.

In such cases we will configure an installed database. To illustrate this example we will use PostgreSql. One can download and install PostgreSql from here. Let us create a new profile and name it as stage. This profile will make use of PostgreSql. For this we have to create application-stage.properties as shown below:

[code]
spring.database.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5433/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
[/code]

The above are the connection url, username and password to connect to Postgres instance. We would have to create the person table in the Postgres instance.

We will also update the pom.xml to comment out the hsqldb dependency and instead add dependency to Postgres driver as shown below:

[code lang=”xml”]
<!– <dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency> –>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc41</version>
</dependency>
[/code]

Let us now run the application by using the command: mvn spring-boot:run -Dspring.profiles.active=stage. You can see the same output you saw with the above run:

[code]
2015-08-20 20:06:23.829 INFO 3676 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : Person saved successfully
2015-08-20 20:06:23.845 INFO 3676 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
[/code]

But in this case if you run it multiple times then you will see multiple entries in the person table as shown below:

[code]
2015-08-20 20:54:21.914 INFO 6924 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : Person saved successfully
2015-08-20 20:54:21.945 INFO 6924 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
2015-08-20 20:54:21.945 INFO 6924 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
[/code]

This is because the data is persistent in this case unlike hsqldb which is in-memory db.

JPA and Spring Data with Spring Boot

Above sections we saw interacting with db using JdbcTemplate. In this section we will see how the same can be achieved using Java Persistance API. Spring Data provides excellent mechanism to achieve the persistence using JPA. First step is to update pom.xml to add dependency on JPA as shown below:

[code lang=”xml”]
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
[/code]

Next we are going to introduce new column in the person table and also create a sequence to auto increment the value in the new column and bind that sequence to the new column being created. Below SQL commands help us achieve that:

[code lang=”sql”]
CREATE SEQUENCE person_id_seq START WITH 1 INCREMENT BY 1;
ALTER TABLE person ADD COLUMN id numeric DEFAULT nextval(‘person_id_seq’);
ALTER SEQUENCE person_id_seq OWNED BY person.id;
[/code]

Next is to create an entity class that maps to the underlying table. Let us create PersonEntity as shown below:

[code lang=”java”]
package net.javabeat;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "person")
public class PersonEntity implements Serializable{

private static final long serialVersionUID = -1801714432822866390L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

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

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

private int age;

private String place;

protected PersonEntity(){

}

public PersonEntity(String firstName, String lastName, int age, String place){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.place = place;
}

public String toString(){
StringBuilder builder = new StringBuilder();
builder.append(this.getId()).append(", ")
.append(this.getFirstName()).append(", ")
.append(this.getLastName()).append(", ")
.append(this.getPlace()).append(", ")
.append(this.getAge());

return builder.toString();
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getPlace() {
return place;
}

public void setPlace(String place) {
this.place = place;
}
}
[/code]

Next is to create a repository class that will provide us with basic APIs to interact with db and also provide facility to add new APIs to interact with db. We will be using the CrudRepository provided by spring data. It provides us with APIs to do CRUD operations and some find operations like findAll, findOne, count. Let us create PersonRepository interface as shown below:

[code lang=”java”]
package net.javabeat;

import org.springframework.data.repository.CrudRepository;

public interface PersonRepository extends CrudRepository<PersonEntity, Long>{
}
[/code]

Next is to update SpringbootSqlDemo class with code to access the db using the PersonRepository and PersonEntity. We will keep the JdbcTemplate code as well. Add the below code to the run method of the SpringbootSqlDemo class:

[code lang=”java”]
logger.info("Using JPA for insert and find");
PersonEntity personEntity = new PersonEntity("fName2", "lName2", 24, "Bangalore");
personEntity = personRepository.save(personEntity);
logger.info("Person with ID: " + personEntity.getId() + " saved successfully");

for ( PersonEntity pEntity : personRepository.findAll()){
logger.info(pEntity.toString());
}
[/code]

The application project structure looks something like:
Spring Boot Spring Data JPALet us run the application by using the command: mvn spring-boot:run -Dspring.profiles.active=stage. You can notice the data inserted and read from JdbcTemplate as well as the data inserted and read using JPA as shown below:

[code lang=”java”]
2015-08-21 06:18:59.054 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : Person saved successfully
2015-08-21 06:18:59.054 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
2015-08-21 06:18:59.054 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
2015-08-21 06:18:59.054 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
2015-08-21 06:18:59.054 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
2015-08-21 06:18:59.054 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
2015-08-21 06:18:59.054 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
2015-08-21 06:18:59.054 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : fName2, lName2, Bangalore, 24
2015-08-21 06:18:59.054 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : FName, LName, Place, 20
2015-08-21 06:18:59.054 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : Using JPA for insert and find
2015-08-21 06:18:59.101 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : Person with ID: 9 saved successfully
2015-08-21 06:18:59.272 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : 1, FName, LName, Place, 20
2015-08-21 06:18:59.272 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : 2, FName, LName, Place, 20
2015-08-21 06:18:59.272 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : 3, FName, LName, Place, 20
2015-08-21 06:18:59.272 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : 4, FName, LName, Place, 20
2015-08-21 06:18:59.272 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : 5, FName, LName, Place, 20
2015-08-21 06:18:59.272 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : 6, FName, LName, Place, 20
2015-08-21 06:18:59.272 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : 7, fName2, lName2, Bangalore, 24
2015-08-21 06:18:59.272 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : 8, FName, LName, Place, 20
2015-08-21 06:18:59.272 INFO 13544 — [tSqlDemo.main()] net.javabeat.SpringbootSqlDemo : 9, fName2, lName2, Bangalore, 24
[/code]

Using JPA reduces lot of boiler plate code. One can even create methods in the Repository class and annotate it with the SQL we want to run. The code used in this article is available in the JavaBeat’s github repository here. (Also originally written in Sanaulla’s repository here).

In this article we saw how we moved from in-memory database to installed databases and also saw how we could use JdbcTemplate and JPA to interact with the db. We didn’t have to write any sort of XML configuration and everything was managed by auto configuration provided by Springboot. Overall, you would have got good idea on how to use SQL Databases and Spring Boot together for persisting the application data.

How are you doing in your projects, please share your experience in our comments section.

Filed Under: Spring Framework Tagged With: SpringBoot Tutorials

Spring Boot : RESTful API using Spring Boot and MongoDB

June 25, 2015 by Mohamed Sanaulla Leave a Comment

This tutorial explains how to implement RESTful web service using SpringBoot and MongoDB. This tutorials uses already implemented REST services using Node.js and ExpressJS frameworks. Here the same examples tested with SpringBoot.

The following are the frameworks used in this tutorial for running the given example. If you are very much interested in learning the REST Web Services concepts, please visit our pal Eugen’s world class video course on BUILD YOUR REST API WITH SPRING.

  • Spring Boot
  • MongoDB
  • ExpressJS
  • Node.js
  • RESTful Concepts

In this post I will implement the REST API designed in one of my previous posts here.

Create RESTful API using Spring Boot and MongoDB
Create RESTful API using Spring Boot and MongoDB

Creating a simple Maven project in Eclipse

The following steps helps you to create a simple Maven project in Eclipse. We have several good tutorials on Maven for the beginners. If you are looking for interesting reads on Maven, please read Apache Maven for Beginners, Create Web Application Project with Maven and How to Build Spring MVC Application with Maven.

Project Type selection

SpringBoot MongoDB RESTAPI
SpringBoot MongoDB RESTAPI

Workspace and archetype selection

SpringBoot MongoDB RESTAPI MAVEN
SpringBoot MongoDB RESTAPI MAVEN

Maven project properties
SpringBoot MongoDB RESTAPI MAVEN 1

The final project structure
SpringBoot MongoDB RESTAPI MAVEN Project

Now that the basic maven based Spring boot is ready, let me give you an overview of Springboot and the idea behind it.

REST API using Spring Boot and MongoDB

What is Spring Boot?

Spring Boot is approach to develop Spring based application with very less configuration. It leverages existing Spring projects as well as Third party projects to develop production ready applications. It provides a set of Starter Pom’s or gradle build files which one can use to add required dependencies and also facilitate auto configuration.

Depending on the libraries on its classpath, Spring Boot automatically configures required classes. For example to interact with DB, if there is Spring Data libraries on class path then it automatically sets up connection to DB along with the Data Source class.

More about Spring Boot can be found here.

Creating RESTful Web Service

I will not show you how to create a RESTful Web Service using Spring Boot. The API which I am going to implement in this post has already been defined in one of my previous posts here.

spring-boot-starter-parent

Lets update the pom.xml to add refer to the parent pom which is: spring-boot-starter-parent. This is the starter pom provided by Spring Boot project. This start pom:

  • sets up the maven properties
  • basic dependency to spring-core
  • setting up location for resource files
  • setting up maven plugins including the plugin provided by spring boot to run its application

[code language=”xml” highlight=”8-15″]
<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>net.javabeat</groupId>
<artifactId>springboot-rest-demo</artifactId>
<version>0.1</version>
<name>Spring Boot REST API Demo</name>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
</project>
[/code]

spring-boot-starter-web

In order to build RESTful Service we would need make use of: spring web, JSON processing libraries, embedded tomcat or tomcat libraries, may be some library for validators like Hibernate validator. We might not remember all the dependencies required or might have to refer to some place to know which dependencies are required.

To solve such issues Spring Boot provides a pom already configured with the dependencies required to build a web application and that pom is called: spring-boot-starter-web. Updating our pom.xml to add it as a dependency we get:

[code language=”xml” highlight=”16-21″]
<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>net.javabeat</groupId>
<artifactId>springboot-rest-demo</artifactId>
<version>0.1</version>
<name>Spring Boot REST API Demo</name>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
[/code]

Similarly we have a pom: spring-boot-starter-data-mongodb which includes dependencies to mongo java driver, spring transaction, spring data for mongodb. So our final pom.xml looks like:

[code language=”xml” highlight=”21-24″]
<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>net.javabeat</groupId>
<artifactId>springboot-rest-demo</artifactId>
<version>0.1</version>
<name>Spring Boot REST API Demo</name>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
</project>
[/code]

Spring Boot Application

We need to create a main class which initializes the Spring Boot application and runs it. We also annotate the class with @SpringBootApplication. This annotation is tells the Spring application to enable autoconfiguration and component scan and also tells the Spring application that this particular class is also a configuration:

[code lang=”java”]
package app;

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

@SpringBootApplication
public class Application {

public static void main(String[] args) throws Exception {
SpringApplication.run(new Object[] { Application.class }, args);
}
}
[/code]

Implementing the RESTful APIs

Let me create a model class to hold Book details retrieved from DB.

[code language=”java”]
package app.model;

import org.springframework.data.annotation.Id;

public class Book {

@Id
private String id;
private String name;
private String isbn;
private String author;
private int pages;

public Book(){}

public Book(String name, String isbn, String author, int pages){
this.name = name;
this.isbn = isbn;
this.author = author;
this.pages = pages;
}

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
}

[/code]

Lets add Repository class to interact with the DB

[code language=”java”]
package app.repository;

import app.model.Book;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface BookRepository extends MongoRepository<Book, String>{
}
[/code]

The MongoRepository provides basic CRUD operation methods and also an API to find all documents in the collection.

Implementing Create and Get Details API

Lets implement our controller. First is the API to create new book and also to get the details of a given book:

[code language=”java”]
package app.controller;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import app.model.Book;
import app.repository.BookRepository;

@RestController
@RequestMapping("/book")
public class BookController {

@Autowired
private BookRepository bookRepository;

@RequestMapping(method = RequestMethod.POST)
public Map<String, Object> createBook(@RequestBody Map<String, Object> bookMap){
Book book = new Book(bookMap.get("name").toString(),
bookMap.get("isbn").toString(),
bookMap.get("author").toString(),
Integer.parseInt(bookMap.get("pages").toString()));

bookRepository.save(book);
Map<String, Object> response = new LinkedHashMap<String, Object>();
response.put("message", "Book created successfully");
response.put("book", book);
return response;
}

@RequestMapping(method = RequestMethod.GET, value="/{bookId}")
public Book getBookDetails(@PathVariable("bookId") String bookId){
return bookRepository.findOne(bookId);
}
}
[/code]

Lets run the application by either using Spring Boot maven plugin i.e by running mvn spring-boot:run or by running the main class Application.java from Eclipse or your IDE. I will use Postman REST Client to invoke the create API:
1

The below is the screenshot from Postman to invoke the Get Book Details API:
2

Implementing Update API

Now lets implement the Update API (just showing the method implemented here, it should be part of the BookController class defined above):

[code language=”java”]
@RequestMapping(method = RequestMethod.PUT, value="/{bookId}")
public Map<String, Object> editBook(@PathVariable("bookId") String bookId,
@RequestBody Map<String, Object> bookMap){
Book book = new Book(bookMap.get("name").toString(),
bookMap.get("isbn").toString(),
bookMap.get("author").toString(),
Integer.parseInt(bookMap.get("pages").toString()));
book.setId(bookId);

Map<String, Object> response = new LinkedHashMap<String, Object>();
response.put("message", "Book Updated successfully");
response.put("book", bookRepository.save(book));
return response;
}
[/code]

Screenshot from Postman REST client after executing the Update:
3

Implementing the Delete API

[code language=”java”]
@RequestMapping(method = RequestMethod.DELETE, value="/{bookId}")
public Map<String, String> deleteBook(@PathVariable("bookId") String bookId){
bookRepository.delete(bookId);
Map<String, String> response = new HashMap<String, String>();
response.put("message", "Book deleted successfully");

return response;
}
[/code]

Screenshot from Postman REST client after executing the Delete:
4

Implementing the Get All Books API

[code language=”java”]
@RequestMapping(method = RequestMethod.GET)
public Map<String, Object> getAllBooks(){
List<Book> books = bookRepository.findAll();
Map<String, Object> response = new LinkedHashMap<String, Object>();
response.put("totalBooks", books.size());
response.put("books", books);
return response;
}
[/code]

Screenshot from Postman REST client after executing the Get all books:

5

With this I have shown you how to build a REST API for CRUD operations using Spring Boot and MongoDB. One can see that with minimum configuration I have been able to write a full fledged implementation of REST API. I hope this tutorial have helped to understand how to write Spring Boot application with MongoDB.

  • Professional Node.js
  • Node.js in Action
  • Node.js Receipes

MongoDB is the popular NoSQL database and Spring Boot is the latest framework from Spring community to run the Spring applications with minimal configurations. Hence, Spring Boot and MongoDB makes good combination to work together for building the RESTful APIs.

If you have any questions on how to write Spring Boot application with MongoDB, please write it in the comments section. Also you can access my Github below for the complete code for Spring Boot and MongoDB integration example. Have a happy reading!!!

The project can be found on Github here.

Filed Under: MongoDB, Spring Framework Tagged With: SpringBoot Tutorials

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved