Gestion Stock Project With Spring boot And Ionic Part 1

Getting Started | Building an Application with Spring Boot






Gestion Stock project with Spring boot and Ionic

In this tutorial We will create an application to stock the product of clients, The user can login and reserve a date then he adds the products and modify or delete his command, product or his account


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.


Create new Spring boot project:

I will use Eclipse Ide for develop this project Eclipse IDe


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

A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects.

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.0</version> <relativePath/> </parent> <groupId>com.gestion-stock</groupId> <artifactId>gestion-stock</artifactId> <version>0.0.1-SNAPSHOT</version> <name>gestion-stock</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/gestion-stock?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 java classes

-> User.java

-> Command.java

-> Product.java

src/main/java/com/gestionstock/model/User.java):

    
  
package com.gestionstock.model; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user") private List<Command> commands; public User() { Suber(); } public User(String username) { Suber(); this.username = username; } public User(String username, List<Command> commands) { Suber(); this.username = username; this.commands = commands; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public List<Command> getCommands() { return commands; } public void setCommands(List<Command> commands) { this.commands = commands; } public void addCommand(Command command) { if (getCommands() == null) { this.commands = new ArrayList<>(); } getCommands().add(command); command.setUser(this); } }

src/main/java/com/gestionstock/model/Command.java):

    
  
package com.gestionstock.model; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "command") public class Command { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Temporal(TemporalType.TIMESTAMP) private Date createAt; private String comment; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "command") private List<Procut> products; @ManyToOne @JsonBackReference(value = "user") private User user; public Command() { Suber(); } public Command(Date createAt, String comment, List<Procut> products, User user) { Suber(); this.createAt = createAt; this.comment = comment; this.products = products; this.user = user; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getCreateAt() { return createAt; } public void setCreateAt(String createAt) { this.createAt = createAt; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } public void addProduct(Product product) { if (getProducts() == null) { this.products = new ArrayList<>(); } getProducts().add(product); product.setCommand(this); } }

src/main/java/com/gestionstock/model/Product.java):

    
  
package com.gestionstock.model; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.*; @Entity @Table(name = "users") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String description; private double price; private int quantity; private String photo; @JsonBackReference(value = "command") @ManyToOne private Command command; public Product() { Suber(); } public Product(String name, String description, double price, int quantity, String photo, Command command) { Suber(); this.name = name; this.description = description; this.price = price; this.quantity = quantity; this.photo = photo; this.command = command; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public Command getCommand() { return command; } public void setCommand(Command command) { this.command = command; } }

JPA Repositories:

JpaRepository is JPA specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting.


Create interfaces and extends the JpaRepository. We have to pass two parameters: type of the entity that it manages and the type of the Id field.

-> UserRepository

-> CommandRepository

-> ProductRepository

src/main/java/com/gestionstock/model/UserRepository.java):

    
  
package com.gestionstock.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.gestionstock.model.User; @Repository public interface UserRepository extends JpaRepository<User, Long> { }

src/main/java/com/gestionstock/model/CommandRepository.java):

    
  
package com.gestionstock.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.gestionstock.model.Command; @Repository public interface CommandRepository extends JpaRepository<Command, Long> { }

src/main/java/com/gestionstock/model/ProductRepository.java):

    
  
package com.gestionstock.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.gestionstock.model.Product; @Repository public interface ProductRepository extends JpaRepository<Product, Long> { }

Services

Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file. The logic for creating a service component class file is shown here


We will create three interfaces in service package:

-> UserService.java

-> CommandService.java

-> ProductService.java

src/main/java/com/gestionstock/service/UserService.java):

    
  
package com.gestionstock.service; import com.gestionstock.model.User; public interface UserService { User saveUser(User user); User getUserByUserId(Long id); User updateUser(User user, Long id); void deleteUser(Long id); }

src/main/java/com/gestionstock/service/CommandService.java):

    
  
package com.gestionstock.service; import java.util.List; import com.gestionstock.model.Command; public interface CommandService { Command findCommandById(Long id); Command saveCommand(Command command, Long idUser); Command updateCommand(Command command, Long id); void deleteCommand(Long id); List<Command> findAllCommandForUser(Long idUser); }

src/main/java/com/gestionstock/service/ProductService.java):

    
  
package com.gestionstock.service; import com.gestionstock.model.Product public interface ProductService { Product findProductById(Long id); Product updateProduct(Product product, Long id); void deleteProduct(Long id); Product saveProduct(Product command, Long idCommand); }

Implements

Here we will use the implements for the Strategy pattern is a software design pattern commonly used for developing User interface that divides the related program logic into three interconnected elements.

The class that implements the Interface with @Component and @Transactional annotations is as shown −

We will create three classes in impl package;

-> UserImpl.java

-> CommandImpl.java

-> ProductImpl.java

src/main/java/com/gestionstock/impl/UserImpl.java):

    
  
package com.gestionstock.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.stereotype.Component; import com.gestionstock.model.User; import com.gestionstock.repository.UserRepository; import com.gestionstock.service.UserService; @Transactional @Component public class UserImpl implements UserService { @Autowired private UserRepository userRepository; @Override public User saveUser(User user) { return userRepository.save(user); } @Override public User getUserByUserId(Long id) { return userRepository.findById(id).get(); } @Override public User updateUser(User user, Long id) { User existUser = userRepository.findById(id).get(); existUser.setUsername(user.getUsername()); return userRepository.save(existUser); } @Override public void deleteUser(Long id) { userRepository.deleteById(id); } }

src/main/java/com/gestionstock/impl/CommandImpl.java):

    
  
package com.gestionstock.impl; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.gestionstock.model.Command; import com.gestionstock.model.User; import com.gestionstock.repository.CommandRepository; import com.gestionstock.repository.UserRepository; import com.gestionstock.service.CommandService; @Transactional @Component public class CommandImpl implements CommandService { @Autowired private CommandRepository commandRepository; @Autowired private UserRepository userRepository; @Override public Command findCommandById(Long id) { return commandRepository.findById(id).get(); } @Override public Command saveCommand(Command command, Long idIUser) { User user = userRepository.getOne(idUser); user.addCommand(command); return commandRepository.save(command); } @Override public Command updateCommand(Command command, Long id) { Command commandExist = commandRepository.getOne(id); commandExist.setCreateAt(new Date()); commandExist.setComment(command.getComment()); return commandRepository.save(commandExist); } @Override public void deleteCommand(Long id) { commandRepository.deleteById(id); } @Override public List<Command> findAllCommandForUser(Long idIUser) { User user = userRepository.getOne(idIUser); return user.getCommands(); } }

src/main/java/com/gestionstock/impl/ProductImpl.java):

    
  
package com.gestionstock.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.gestionstock.model.Command; import com.gestionstock.model.Product; import com.gestionstock.repository.CommandRepository; import com.gestionstock.repository.ProductRepository; import com.gestionstock.service.ProductService; @Transactional @Component public class ProductImpl implements ProductService { @Autowired private CommandRepository commandRepository; @Autowired private ProductRepository productRepository; @Override public Product findProductById(Long id) { return ProductRepository productRepository.findById(id).get(); } @Override public Product updateProduct(Product product, Long id) { Product productExists = productRepository.getOne(id); productExists.setName(product.getName()); productExists.setDescription(product.getDescription()); productExists.setPrice(product.getPrice()); productExists.setQuantity(product.getQuantity()); productExists.setPhoto(product.getPhoto()); return productRepository.save(productExists); } @Override public void deleteProduct(Long id) { productRepository.deleteById(id); } @Override public Product saveProduct(Product product, Long idCommand) { Command command = commandRepository.getOne(idCommand); command.addProduct(product); return productRepository.save(product); } }

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

-> UserController.java

-> CommandController.java

-> ProductController.java

src/main/java/com/gestionstock/controller/UserController.java):

    
  
package com.gestionstock.controller; import org.springframework.beans.factory.annotation.Autowired; 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.gestionstock.model.User; import com.gestionstock.service.UserService; @CrossOrigin(origins = "*") @RestController @RequestMapping("/api") public classs UserController { @Autowired private UserService userService; @PostMapping("/saveUser") User saveUser(@RequestBody User user) { return userService.saveUser(user); } @GetMapping("/getUserByUserId/{id}") User getUserByUserId(@PathVariable Long id) { return userService.getUserByUserId(id); } @PutMapping("/updateUser/{id}") User updateUser(@RequestBody User user, @PathVariable Long id){ return userService.updateUser(user, id); } @DeleteMapping("/deleteUser/{id}") void deleteUser(@PathVariable Long id) { userService.deleteUser(id); } }

src/main/java/com/gestionstock/controller/CommandController.java):

    
  
package com.gestionstock.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.gestionstock.model.Command; import com.gestionstock.service.CommandService; import java.util.List; @CrossOrigin(origins = "*") @RestController @RequestMapping("/api") public class CommandController { @Autowired private CommandService commandService; @GetMapping("/findCommandById/{id}") Command findCommandById(@PathVariable Long id) { return commandService.findCommandById(id); } @PostMapping("/saveCommand/{idUser}") Command saveCommand(@RequestBody Command command, @PathVariable Long idUser) { return commandService.saveCommand(command, idUser); } @PutMapping("/updateCommand/{id}") Command updateCommand(@RequestBody Command command, @PathVariable Long id) { return commandService.updateCommand(command, id); } @DeleteMapping("/deleteCommand/{id}") void deleteCommand(@PathVariable Long id) { commandService.deleteCommand(id); } @GetMapping("/findAllCommandForUser/{idUser}") List<Command> findAllCommandForUser(@PathVariable Long idUser){ return commandService.findAllCommandForUser(idUser); } }

src/main/java/com/gestionstock/controller/ProductController.java):

    
  
package com.gestionstock.controller; import org.springframework.beans.factory.annotation.Autowired; 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.gestionstock.model.Product; import com.gestionstock.service.ProductService; @CrossOrigin(origins = "*") @RestController @RequestMapping("/api") public classs ProductController { @Autowired private ProductService productService; @GetMapping("/findProductById/{id}") Product findProductById(@PathVariable Long id) { return productService.findProductById(id); } @PutMapping("/updateProduct/{id}") Product updateProduct(@RequestBody Product product, @PathVariable Long id) { return productService.updateProduct(product, id); } @DeleteMapping("/deleteProduct/{id}") void deleteProduct(@PathVariable Long id) { productService.deleteProduct(id); } @PostMapping("/saveProduct/{idCommand}") Product saveProduct(@RequestBody Product product, @PathVariable Long idCommand) { return productService.saveProduct(product, idCommand); } }

Application.java

We need to run Application.run() because this method starts whole Spring Framework. Code below integrates your main() with Spring Boot.

src/main/java/com/gestionstock/Application.java):

    
  
package com.gestionstock; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GestionStockApplication { public static void main(String[] args) { SpringApplication.run(GestionStockApplication.class, args); System.out.print("\nApp Started ..."); } }


Conclusion

We were building this application with functionality:

- Created a package model inside it We will add java classes
- JpaRepository is JPA specific extension of Repository.
- created three interfaces in service package:
- The class that implements the Interface with @Component and @Transactional annotations
- @RestController is a convenience annotation for creating Restful controllers.

Post a Comment

Previous Post Next Post


Follow us on facebook