Application Restaurant With Spring and Angular use Mongodb Part 1

Getting Started | Building an Application with Spring Boot






Restaurant Application Spring boot and Angular use Mongodb

In this tutorial We going to develop an application restaurant to display all the places and we can search by name or cuisine. backend side is made with Spring boot


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 project

pom.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.restuarent</groupId> <artifactId>restuarent</artifactId> <version>0.0.1-SNAPSHOT</version> <name>restuarent</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 restaurants

src/main/resources/application.properties

    
  
  
spring.data.mongodb.database=restaurants 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

-> Restaurant.java

src/main/java/com/restuarent/model/Restaurant.java):



package com.restuarent.model; import java.io.Serializable; import java.util.List; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "restaurant") public class Restaurant implements Serializable { private static final long serialVersionUID = 1L; private String restaurant_id; private String name; private String borough; private String cuisine; private Address address; @DBRef private List<Grade> grades; public Restaurant() { super(); } public Restaurant(String restaurant_id, String name, String borough, String cuisine, Address address, List<Grade> grades) { super(); this.restaurant_id = restaurant_id; this.name = name; this.borough = borough; this.cuisine = cuisine; this.address = address; this.grades = grades; } public String getRestaurant_id() { return restaurant_id; } public void setRestaurant_id(String restaurant_id) { this.restaurant_id = restaurant_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBorough() { return borough; } public void setBorough(String borough) { this.borough = borough; } public String getCuisine() { return cuisine; } public void setCuisine(String cuisine) { this.cuisine = cuisine; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public List<Grade> getGrades() { return grades; } public void setGrades(List<Grade> grades) { this.grades = grades; } }

Here, we are creating @Document

-> Address.java

src/main/java/com/restuarent/model/Address.java):



package com.restuarent.model; import java.io.Serializable; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="address") public class Address implements Serializable { private static final long serialVersionUID = 1L; private String building; private String street; private String zipcode; private Double coord[]; public Address() { super(); } public Address(String building, String street, String zipcode, Double[] coord) { super(); this.building = building; this.street = street; this.zipcode = zipcode; this.coord = coord; } public String getBuilding() { return building; } public void setBuilding(String building) { this.building = building; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } public Double[] getCoord() { return coord; } public void setCoord(Double[] coord) { this.coord = coord; } }

Here, we are creating @Document

-> Grade.java

src/main/java/com/restuarent/model/Grade.java):



package com.restuarent.model; import java.io.Serializable; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "grades") public class Grade implements Serializable { private static final long serialVersionUID = 1L; @DBRef private String grade[]; @DBRef private Integer score[]; public Grade() { super(); } public Grade(String[] grade, Integer[] score) { super(); this.grade = grade; this.score = score; } public String[] getGrade() { return grade; } public void setGrade(String[] grade) { this.grade = grade; } public Integer[] getScore() { return score; } public void setScore(Integer[] score) { this.score = score; } }

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:

-> RestaurantDao.java

src/main/java/com/restuarent/dao/RestaurantDao.java):



package com.restuarent.dao; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import com.restuarent.model.Restaurant; import java.lang.String; public interface RestaurantDao extends MongoRepository<Restaurant, String> { @Query("{restaurant_id : ?0}") List<Restaurant> findRestaurant_id(String restaurant_id); @Query("{borough : ?0}") List<Restaurant> findBorough(String borough); @Query("{cuisine : ?0}") List<Restaurant> findCuisine(String cuisine); List<Restaurant> findByName(String name); List<Restaurant> findByAddressZipcode(String zipCode); }

-> GradeResposigory.java

src/main/java/com/restuarent/dao/GradeResposigory.java):



package com.restuarent.dao; import org.springframework.data.mongodb.repository.MongoRepository; import com.restuarent.model.Grade; public interface GradeResposigory extends MongoRepository<Grade, String> { }

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

-> RestaurantController.java

src/main/java/com/restuarent/controller/RestaurantController.java):



package com.restuarent.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.RestController; import com.restuarent.dao.RestaurantDao; import com.restuarent.model.Restaurant; @RestController @CrossOrigin(origins = "*") public class RestaurantController { @Autowired private RestaurantDao restaurantDao; public RestaurantController(RestaurantDao restaurantDao) { this.restaurantDao = restaurantDao; } @GetMapping("/findAllRestaurants") public List<Restaurant> findRestaurants() { List<Restaurant> restaurants = restaurantDao.findAll(); List<Restaurant> soredList = restaurants.stream().sorted(Comparator.comparing(Restaurant::getRestaurant_id)).limit(20) .collect(Collectors.toList()); return soredList; } @GetMapping("/findRestaurantById={restaurant_id}") public List<Restaurant> findRestaurantById(@PathVariable("restaurant_id") String restaurant_id) { return restaurantDao.findRestaurant_id(restaurant_id); } @GetMapping("/findAllRestaurants/borough={borough}") public List<Restaurant> findRestaurantsBorough(@PathVariable("borough") String borough) { return restaurantDao.findBorough(borough); } @GetMapping("/findAllRestaurants/Burger-king") public List<Restaurant> findRestaurantsGrade() { return restaurantDao.findByName("Burger King"); } @GetMapping("/findAllRestaurants/pizza") public List<Restaurant> findRestaurantsPizza() { return restaurantDao.findCuisine("Pizza"); } @GetMapping("/findAllRestaurants/zipcode") public List<Restaurant> findByAddressZipcode() { List<Restaurant> restaurants = restaurantDao.findByAddressZipcode("10001"); List<Restaurant> soredList = restaurants.stream().sorted(Comparator.comparing(Restaurant::getRestaurant_id)).limit(50) .collect(Collectors.toList()); return soredList; } @GetMapping("/findAllRestaurants/name={name}") public List<Restaurant> findRestaurantsByName(@PathVariable("name") String name) { return restaurantDao.findByName(name); } }


Application Configuation

@Configuration & @Bean Annotations Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. The simplest possible @Configuration class would be as follows −


Now, we need to create Java Based Configuration

-> ApplicationConfig.java

src/main/java/com/restuarent/ApplicationConfig.java):



package com.restuarent; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @ComponentScan @EnableWebMvc public class ApplicationConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { // Can just allow `methods` that you need. registry.addMapping("/**").allowedMethods("PUT", "GET", "DELETE", "OPTIONS", "PATCH", "POST"); } }


RestuarentApplication

@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

-> RestuarentApplication.java

src/main/java/com/restuarent/RestuarentApplication.java):



package com.restuarent; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RestuarentApplication { public static void main(String[] args) { SpringApplication.run(RestuarentApplication.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.





Post a Comment

Previous Post Next Post


Follow us on facebook