Crud Customer Application Spring boot and Angular Part 1

Getting Started | Building an Application with Spring Boot






Crud Customer Application Spring boot and Angular

In this tutorial, we are going to develop a CRUD (create-read-update-delete) web application. This application contains the student form that includes the CRUD features like add, view, delete, and update student. In this integration, we are using Spring Boot to handle the backend part and Angular to handle the frontend part.


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).

° MySQL 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.


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.curd-customer</groupId> <artifactId>curd-customer</artifactId> <version>0.0.1-SNAPSHOT</version> <name>curd-customer</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-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </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 gestion-stock

src/main/resources/application.properties

    
  
  
spring.datasource.url=jdbc:mysql://localhost:3306/crud-customer?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC spring.datasource.username=root spring.activemq.password= spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.ddl-auto=create-drop server.port=8080

Class Diagram



First We Will Create a package model inside it We will add Customer Class

Here, we are creating an Entity

-> Customer.java

src/main/java/com/curdcustomer/model/Customer.java):



package com.curdcustomer.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstname; private String lastname; private int age; private boolean active; public Customer() { super(); } public Customer(String firstname, String lastname, int age, boolean active) { super(); this.firstname = firstname this.lastname = lastname this.age = age this.active = active } 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 boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }

Here, we are creating the DAO interface to perform database related operations.

src/main/java/com/curdcustomer/repository/CustomerRepository.java):



package com.curdcustomer.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.curdcustomer.model.Customer; @Repository public interface CustomerRepository extends JpaRepository<Customer, Long> { List<Customer> findByAge(int age); }

Here, we are creating a service layer interface that acts as a bridge between DAO and Entity classes.

src/main/java/com/curdcustomer/service/CustomerService.java):



package com.curdcustomer.service; import java.util.List; import java.util.Optional; import org.springframework.http.ResponseEntity; import com.curdcustomer.model.Customer; public interface CustomerService { Customer create(Customer customer); ResponseEntity<Customer> update(Customer customer, Long id); ResponseEntity<Customer> isActive(Customer customer, Long id); ResponseEntity<Customer> inActive(Customer customer, Long id); List<Customer> getAllCustomers(); ResponseEntity<String> deleteAllCustomers(); ResponseEntity<String> deleteCustomer(long id); Optional<Customer> findById(long id); List<Customer> findByAge(int age); }

Create the service layer implementation class

src/main/java/com/impl/service/CustomerServiceImpl.java):



package com.curdcustomer.impl; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import com.curdcustomer.model.Customer; import com.curdcustomer.repository.CustomerRepository; import com.curdcustomer.service.CustomerService; @Component @Transactional public class CustomerServiceImpl implements CustomerService { @Autowired private CustomerRepository customerRepository; @Override public Customer create(Customer customer) { return customerRepository.save(customer); } @Override public ResponseEntity<Customer> update(Customer customer, Long id) { Optional<Customer> customerDataOptional = customerRepository.findById(id); if (customerDataOptional.isPresent()) { Customer _Customer = customerDataOptional.get(); _Customer.setFirstname(customer.getFirstname()); _Customer.setLastname(customer.getLastname()); _Customer.setAge(customer.getAge()); return new ResponseEntity<Customer>(customerRepository.save(_Customer), HttpStatus.OK); } else { return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND); } } @Override public List<Customer> getAllCustomers() { List<Customer> customers = customerRepository.findAll(); customers = customers.stream().sorted(Comparator.comparing(Customer::getAge)) .collect(Collectors.toList()); return customers; } @Override public ResponseEntity<String> deleteAllCustomers() { customerRepository.deleteAll(); return new ResponseEntity<String>("All customer have been deleted!", HttpStatus.OK); } @Override public ResponseEntity<String> deleteCustomer(long id) { customerRepository.deleteById(id); return new ResponseEntity<String>("Customer has been deleted!", HttpStatus.OK); } @Override public Optional<Customer> findById(long id) { Optional<Customer> customers = customerRepository.findById(id); return customers; } @Override public List<Customer> findByAge(int age) { List<Customer> customers = customerRepository..findByAge(age); return customers; } @Override public ResponseEntity<Customer> isActive(Customer customer, Long id) { Optional<Customer> customerDataOptional = customerRepository.findById(id); if (customerDataOptional.isPresent()) { Customer _Customer = customerDataOptional.get(); _Customer.setActive(true); return new ResponseEntity<Customer>(customerRepository..save(_Customer), HttpStatus.OK); } else { return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND); } } @Override public ResponseEntity<Customer> inActive(Customer customer, Long id) { Optional<Customer> customerDataOptional = customerRepository.findById(id); if (customerDataOptional.isPresent()) { Customer _Customer = customerDataOptional.get(); _Customer.setActive(false); return new ResponseEntity<Customer>(customerRepository.save(_Customer), HttpStatus.OK); } else { return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND); } } }

Create the controller class

src/main/java/com/curdcustomer/controller/CustomerController.java):



package com.curdcustomer.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.curdcustomer.model.Customer; import com.curdcustomer.service.CustomerService; @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api") public class CustomerController { @Autowired private CustomerService customerService; @PostMapping(value="/customers/create") public Customer create(@RequestBody Customer customer) { return customerService.create(customer); } @GetMapping(value="/customers/getAllCustomers") public List<Customer> getAllCustomers(){ return customerService.getAllCustomers(); } @PutMapping(value="/customers/update/{id}") public ResponseEntity<Customer> update(@RequestBody Customer customer, @PathVariable("id") Long id){ return customerService.update(customer, id); } @DeleteMapping(value="/customers/deleteAllCustomers") public ResponseEntity@lt;String> deleteAllCustomers() { return customerService.deleteAllCustomers(); } @DeleteMapping(value="/customers/delete/{id}") public ResponseEntity<String> deleteCustomer(@PathVariable("id") long id){ return customerService.deleteCustomer(id); } @GetMapping(value="customers/id/{id}") Optional<Customer> findById(@PathVariable long id) { return customerService.findById(id); } @GetMapping(value="customers/age/{age}") public List<Customer> findByAge(@PathVariable int age){ return customerService.findByAge(age); } @PutMapping(value="/customers/isActive/{id}") public ResponseEntity<Customer> isActive(@RequestBody Customer customer, @PathVariable Long id) { return customerService.isActive(customer, id); } @PutMapping(value="/customers/inActive/{id}") ResponseEntity<Customer> inActive(@RequestBody Customer customer, @PathVariable Long id) { return customerService.inActive(customer, id); } }

src/main/java/com/curdcustomer/CurdCustomerApplication.java):



package com.curdcustomer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CurdCustomerApplication { public static void main(String[] args) { SpringApplication.run(CurdCustomerApplication.class, args); System.out.print("App started..."); } }

Conclusion

Now we have an overview of Spring Boot CRUD example when building a CRUD App.

We also take a look at client-server architecture for REST API using Spring Web MVC & Spring Data JPA, 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