Intro
This post is a beginner's guide to getting started with creating a simple REST API within seconds using Spring Boot and MongoDB.Contains all basic CRUD operations.
Few confusions I faced as a beginner was when packaging was done and Spring Boot could locate several components.
So this blog post will follow the standard packaging alongside the implementation.
For further understanding of the annotations to be used, [1] and [2] can be referenced
Prerequisites
- Maven
- MongoDB setup
Code
Step 1 : Initiate maven directory structure
|__src
|__main
|__java
|__com.example.project
|__resources
|__test
Initiate the pom.xml as below. Here, the mongoDB dependency is added as well.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example.project</groupId> <artifactId>movie-reservation</artifactId> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.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> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Step 2 : Initiating Spring Boot Application
|__src
|__main
|__java
|__com.example.project
|__Application.java
Application.java
package com.example.project; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application implements CommandLineRunner{ public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... strings) throws Exception { } }
Step 3 : Implementing the Model
Next, we have to implement the model which will represent the entity in the database.
|__src
|__main
|__java
|__com.example.project
|__models
|__Movie.java
|__Application.java
Movie.java
package com.example.project.models; import org.springframework.data.annotation.Id; import java.io.Serializable; public class Movie implements Serializable{ @Id public String id; public String name; public int releasedYear; public Movie() {} public Movie(String name, int releasedYear) { this.name = name; this.releasedYear = releasedYear; } @Override public String toString() { return "Movie{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", releasedYear=" + releasedYear + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Movie movie = (Movie) o; if (releasedYear != movie.releasedYear) return false; if (id != null ? !id.equals(movie.id) : movie.id != null) return false; return name != null ? name.equals(movie.name) : movie.name == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + releasedYear; return result; } }
Step 5: Implementing a repository
Next, we should implement a repository which will handle the database.
|__src
|__main
|__java
|__com.example.project
|__models
|__Movie.java
|__repositories
|__MovieRepository.java
|__repositories
|__MovieRepository.java
|__Application.java
MovieRepository.java
package com.example.project.repositories; import com.example.project.models.Movie; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; @Repository public interface MovieRepository extends MongoRepository<Movie,String>{ }
We do not have explicitly implement the basic operations to the DB. They are already defined in MongoRepository. And they will be inherited to MovieRepository here.
Step 6: Implementing a service
We will now implement a service that handle the manipulations done to this model.
|__MovieService.java
|__MovieServiceImpl.java
|__src
|__main
|__java
|__com.example.project
|__models
|__Movie.java
|__repositories
|__MovieRepository.java
|__services|__repositories
|__MovieRepository.java
|__MovieService.java
|__MovieServiceImpl.java
|__Application.java
MovieService.java
package com.example.project.services; import com.example.project.Movie; import java.util.List; public interface MovieService { List<Movie> getAllMovies(); Movie getMovieById(String id); Movie addMovie(Movie movie); Movie updateMovie(Movie movie); void deleteMovie(String id); }
MovieServiceImpl.java
package com.example.project.services; import com.example.project.models.Movie; import com.example.project.repositories.MovieRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class MovieServiceImpl implements MovieService { @Autowired private MovieRepository movieRepository; public List<Movie> getAllMovies(){ return movieRepository.findAll(); } @Override public Movie getMovieById(String id) { return movieRepository.findOne(id); } @Override public Movie addMovie(Movie movie) { return movieRepository.save(movie); } @Override public Movie updateMovie(Movie movie) { return movieRepository.save(movie); } @Override public void deleteMovie(String id) { movieRepository.delete(id); } }
Step 7: Implementing the controller
|__src
|__main
|__java
|__com.example.project
|__controllers
|__MovieController.java
|__controllers
|__MovieController.java
|__models
|__Movie.java
|__repositories
|__MovieRepository.java
|__services|__repositories
|__MovieRepository.java
|__MovieService.java
|__MovieServiceImpl.java
|__Application.java
MovieController.java
package com.example.package.controllers; import com.example.package.models.Movie; import com.example.package.services.MovieService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class MovieController { @Autowired private MovieService movieService; @ResponseBody @RequestMapping(value = "/movies", method = RequestMethod.GET) public List<Movie> getAllMovies() { return movieService.getAllMovies(); } @ResponseBody @RequestMapping(value = "/movies/{id}", method = RequestMethod.GET) public Movie getMovieByName(@PathVariable String id) { return movieService.getMovieById(id); } @ResponseBody @RequestMapping(value = "/movies", method = RequestMethod.POST) public Movie addMovie(@RequestBody Movie movie) { return movieService.addMovie(movie); } @ResponseBody @RequestMapping(value = "/movies", method = RequestMethod.PUT) public Movie updateMovie(@RequestBody Movie movie) { return movieService.updateMovie(movie); } @ResponseBody @RequestMapping(value = "/movies/{id}", method = RequestMethod.DELETE) public String deleteMovie(@PathVariable String id) { movieService.deleteMovie(id); return "Deleted"; } }
When @RequestBody is used, the JSON request body will automatically be mapped to a object specified. In this case, it is Movie. For this, the model class must have a default constructor. Else, you will get an error.
By using @ResponseBody, the response will be automatically parsed to JSON.
@PathVariable is used to retrieve URL parameters.
Comments
Post a Comment