Getting Started | Building an Application with Spring Boot
Build an application movies with Spring boot and Angular use Mongodb
In this tutorial We are going build an application Movies to display the movies we will use the query find by title, find by year, find by director and find by actor. we use mongodb database to develope this project.
Tools to be used
° Use any IDE to develop the Spring and Hibernate project. It may be STS/Eclipse/Netbeans. Here, we are using STS (Spring Tool Suite).
° Mongodb for the database.
° Use any IDE to develop the Angular project. It may be Visual Studio Code/Sublime. Here, we are using Visual Studio Code.
° Server: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere.
Spring MVC
Spring MVC is the primary web framework built on the Servlet API. It is build on the popular MVC design pattern. MVC (Model-View-Controller) is a software architecture pattern, which separates application into three areas: model, view, and controller. The model represents a Java object carrying data. The view represents the visualization of the data that the model contains. The controller controls the data flow into model object and updates the view when the data changes. It separates the view and model.
Spring Boot Architecture
Spring Boot is a module of the Spring Framework. It is used to create stand-alone, production-grade Spring Based Applications with minimum efforts. It is developed on top of the core Spring Framework.
Introduction to MongoDB
MongoDB is a document database designed for ease of development and scaling. The Manual introduces key concepts in MongoDB, presents the query language, and provides operational and administrative considerations and procedures as well as a comprehensive reference section.
Dwonload database used in this projectpom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0>/modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/>
</parent>
<groupId>com.movies</groupId>
<artifactId>movies</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>movies</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.8.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Properties File
Properties files are used to keep ‘N’ number of properties in a single file to run the application in a different environment. In Spring Boot, properties are kept in the application.properties file under the classpath.
The application.properties file is located in the src/main/resources directory. The code for sample application.properties
We need to create database name it movies
src/main/resources/application.properties
spring.data.mongodb.database=movies
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
server.port=8080
Class Diagram
First We Will Create a package model inside it We will add three Classes
Here, we are creating @Document
-> Actor.java
src/main/java/com/movies/model/Actor.java):
package com.movies.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "actors")
public class Actor {
@Id
@Field(value="_id")
private String _id;
@Field(value="role")
private String role;
public Actor(String _id, String role) {
super ();
this._id = _id;
this.role = role;
}
public Actor() {
super ();
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
Here, we are creating @Document
-> Artiste.java
src/main/java/com/movies/model/Artiste.java):
package com.movies.model;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "artistes")
public class Artiste {
@Field(value = "_id")
private String _id;
@Field(value = "last_name")
private String last_name;
@Field(value = "first_name")
private String first_name;
@Field(value = "birth_date")
private String birth_date;
public Artiste() {
super();
}
public Artiste(String _id, String last_name, String first_name, String birth_date) {
super();
this._id = _id;
this.last_name = last_name;
this.first_name = first_name;
this.birth_date = birth_date;
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getBirth_date() {
return birth_date;
}
public void setBirth_date(String birth_date) {
this.birth_date = birth_date;
}
}
Here, we are creating @Document
-> Director.java
src/main/java/com/movies/model/Director.java):
package com.movies.model;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "director")
public class Director {
@Field(value = "_id")
private String _id;
public Director() {
psuper ();
}
public Director(String _id) {
psuper ();
this._id = _id;
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
}
Here, we are creating @Document
-> Movie.java
src/main/java/com/movies/model/Movie.java):
package com.movies.model;
import java.util.List;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "movies")
public class Movie {
@Field(value="_id")
private String _id;
@Field(value="title")
private String title;
@Field(value="genre")
private String genre;
@Field(value="summary")
private String summary;
@Field(value="country")
private String country;
@Field(value="year")
private int year;
private Director director;
@DBRef
private List<Actor> actors;
public Movie() {
super();
}
public Movie(String _id, String title, String genre, String summary, String country, int year, Director director,
List<Actor> actors) {
super();
this._id = _id;
this.title = title;
this.genre = genre;
this.summary = summary;
this.country = country;
this.year = year;
this.director = director;
this.actors = actors;
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getYear() {
return year;
}
public voidsetYear(int year) {
this.year = year;
}
public Director getDirector() {
return director;
}
public void setDirector(Director director) {
this.director = director;
}
public List<Actor> getActors() {
return actors;
}
public voidsetActors(List<Actor> actors) {
this.actors = actors;
}
}
MongoTemplate and MongoRepository
The MongoTemplate follows the standard template pattern in Spring and provides a ready to go, basic API to the underlying persistence engine.
The repository follows the Spring Data-centric approach and comes with more flexible and complex API operations, based on the well-known access patterns in all Spring Data projects. For both, we need to start by defining the dependency – for example, in the pom.xml, with Maven:
Now, we need to create a repository – extending the existing MongoRepository interface:
-> ArtisteRepository.java
src/main/java/com/movies/dao/ArtisteRepository.java):
package com.movies.dao;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.movies.model.Artiste;
public interface ArtisteRepository extends MongoRepository<Artiste, Integer> {
}
-> MovieRepository.java
src/main/java/com/movies/dao/MovieRepository.java):
package com.movies.dao;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.movies.model.Movie;
import java.util.List;
import org.springframework.data.mongodb.repository.Query;
import java.lang.String;
public interface MovieRepository extends MongoRepository<Movie, Integer> {
List<Movie> findBy_id(String _id);
@Query("{title : ?0}")
Movie findByTitleQuery(String title);
@Query("{_id : ?0}")
Movie findBy_idQuery(String _id);
@Query("{year : ?0}")
List<Movie> findByYear(int year);
@Query(value = "{'director._id' : ?0}")
List<Movie> findDirectorBy_id(String _id);
@Query(value = "{'actors._id' : ?0}")
List<Movie> findActorsBy_id(String _id);
@Query("{title : {$regex : ?0}}")
List<Movie> findByTitle(String title);
@Query("{'year' : {$gt : ?0, $lt : ?1}}")
List<Movie> findMovieBetweenQuery(int start, int end);
}
Spring Boot @RestController
@RestController is a convenience annotation for creating Restful controllers. It is a specialization of @Component and is autodetected through classpath scanning. It adds the @Controller and @ResponseBody annotations. It converts the response to JSON or XML. It does not work with the view technology, so the methods cannot return ModelAndView. It is typically used in combination with annotated handler methods based on the @RequestMapping annotation.
Now, we need to create a controller class
-> ArtisteController.java
src/main/java/com/movies/model/ArtisteController.java):
package com.movies.controller;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.issamdrmas.dao.ArtisteRepository;
import com.issamdrmas.model.Artiste;
@RestController
@CrossOrigin(origins = "*")
public class ArtisteController {
@Autowired
ArtisteRepository artisteRepository;
@GetMapping("/findAllArtists")
public List<Artiste> findArtistes() {
List<Artiste> artistes = artisteRepository.findAll();
artistes = artistes.stream().sorted(Comparator.comparing(Artiste::get_id).reversed())
.collect(Collectors.toList());
return artistes;
}
}
-> MovieController.java
src/main/java/com/movies/controller/MovieController.java):
package com.issamdrmas.controller;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.issamdrmas.dao.MovieRepositpry;
import com.issamdrmas.model.Movie;
@RestController
@CrossOrigin(origins = "*")
public class MovieController {
@Autowired
MovieRepositpry movieRepositpry;
@GetMapping("/findAllMovies")
public List<Movie> findMovies() {
List<Movie> list = movieRepositpry.findAll();
list = list.stream().sorted(Comparator.comparing(Movie::get_id).reversed())
.collect(Collectors.toList());
return list;
}
@GetMapping("/movie/details={_id}")
public List<Movie> getMovieDetails(@PathVariable("_id") String _id) {
return movieRepositpry.findBy_id(_id);
}
@RequestMapping(value = "/movie/title", method = RequestMethod.GET)
public Movie getMovieByTilte() {
return movieRepositpry.findByTitleQuery("Alien");
}
@RequestMapping(value = "/movie/years", method = RequestMethod.GET)
public List<Movie> getMovieByYear() {
return movieRepositpry.findByYear(1979);
}
@RequestMapping(value = "/movie/id", method = RequestMethod.GET)
public Movie getMovieById() {
return movieRepositpry.findBy_idQuery("movie:2");
}
@RequestMapping(value = "/movie/directoryId", method = RequestMethod.GET)
public List<Movie> getMovieBydirectoryId() {
return movieRepositpry.findDirectorBy_id("artist:4");
}
@RequestMapping(value = "/movie/search", method = RequestMethod.GET)
public List<Movie> getMovieByTitle() {
return movieRepositpry.findByTitle("Re");
}
@RequestMapping(value = "/movie/between/year", method = RequestMethod.GET)
public List<Movie> getMovieByBetweenYeare() {
List<Movie> movies = movieRepositpry.findMovieBetweenQuery(2000, 2005);
movies = movies.stream().sorted(Comparator.comparing(Movie::getYear))
.collect(Collectors.toList());
return movies;
}
@RequestMapping(value = "/movie/actor/id=23", method = RequestMethod.GET)
public List<Movie> findActorsBy_idAndTitle() {
return movieRepositpry.findActorsBy_id("artist:23");
}
MoviesApplication
@SpringBootApplication and its use in a simple Spring Boot application. We use the @SpringBootApplication annotation in our Application or Main class to enable a host of features, e.g. Java-based Spring configuration, component scanning, and in particular for enabling Spring
Now, we need to run RestuarentApplication and main method
-> MoviesApplication.java
src/main/java/com/movies/MoviesApplication.java):
package com.movies;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MoviesApplication {
public static void main(String[] args) {
SpringApplication.run(MoviesApplication.class, args);
System.out.println("App started...");
}
}
Conclusion
Now we have an overview of Spring Boot for backend example when building a App when use the mecroservice.
We also take a look at client-server architecture for REST API using Spring Web MVC & we used MongoDB, as well, we are gooing to continue with Angular 10 project structure for building a front-end app to make HTTP requests and consume responses.