Четвёртая лабораторная работа. Backend

This commit is contained in:
abazov73 2023-04-25 00:35:21 +04:00
parent 61813642af
commit 5568a57217
36 changed files with 596 additions and 386 deletions

View File

@ -22,6 +22,7 @@ dependencies {
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5' implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.hibernate.validator:hibernate-validator'
} }
tasks.named('test') { tasks.named('test') {

Binary file not shown.

View File

@ -0,0 +1,56 @@
package com.example.ipLab.StoreDataBase.Controllers;
import com.example.ipLab.StoreDataBase.DTO.CustomerDTO;
import com.example.ipLab.StoreDataBase.Model.Customer;
import com.example.ipLab.StoreDataBase.Service.CustomerService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/customer")
public class CustomerController {
private final CustomerService customerService;
public CustomerController(CustomerService customerService){
this.customerService = customerService;
}
@GetMapping("/{id}")
public CustomerDTO getCustomer(@PathVariable Long id){
return new CustomerDTO(customerService.getCustomer(id));
}
@GetMapping
public List<CustomerDTO> getCustomers(){
return customerService.getAllCustomers().stream()
.map(CustomerDTO::new)
.toList();
}
@PostMapping
public CustomerDTO createCustomer(@RequestParam("customerLastName") String customerLastName,
@RequestParam("customerFirstName") String customerFirstName,
@RequestParam("customerMiddleName") String customerMiddleName){
final Customer customer = customerService.addCustomer(customerLastName, customerFirstName, customerMiddleName);
return new CustomerDTO(customer);
}
@PutMapping("/{id}")
public CustomerDTO updateCustomer(@RequestParam("customerLastName") String customerLastName,
@RequestParam("customerFirstName") String customerFirstName,
@RequestParam("customerMiddleName") String customerMiddleName,
@PathVariable Long id){
return new CustomerDTO(customerService.updateCustomer(id, customerLastName, customerFirstName, customerMiddleName));
}
@DeleteMapping("/{id}")
public CustomerDTO deleteCustomer(@PathVariable Long id){
return new CustomerDTO(customerService.deleteCustomer(id));
}
@DeleteMapping()
public void deleteAllCustomers(){
customerService.deleteAllCustomers();
}
}

View File

@ -0,0 +1,58 @@
package com.example.ipLab.StoreDataBase.Controllers;
import com.example.ipLab.StoreDataBase.DTO.OrderedDTO;
import com.example.ipLab.StoreDataBase.Model.Ordered;
import com.example.ipLab.StoreDataBase.Service.CustomerService;
import com.example.ipLab.StoreDataBase.Service.OrderService;
import com.example.ipLab.StoreDataBase.Service.ProductService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
public class OrderedController {
private final OrderService orderedService;
private final ProductService productService;
private final CustomerService customerService;
public OrderedController(OrderService orderedService, ProductService productService, CustomerService customerService){
this.productService = productService;
this.customerService = customerService;
this.orderedService = orderedService;
}
@GetMapping("/{id}")
public OrderedDTO getOrdered(@PathVariable Long id){
return new OrderedDTO(orderedService.getOrder(id));
}
@GetMapping
public List<OrderedDTO> getOrdereds(){
return orderedService.getAllOrders().stream()
.map(OrderedDTO::new)
.toList();
}
@PostMapping
public OrderedDTO createOrdered(@RequestParam("productId") Long productId,
@RequestParam("customerId") Long customerId,
@RequestParam("quantity") Integer quantity){
final Ordered ordered = orderedService.addOrder(productService.getProduct(productId), customerService.getCustomer(customerId), quantity);
return new OrderedDTO(ordered);
}
@PutMapping("/{id}")
public OrderedDTO updateOrdered(@RequestParam("quantity") Integer quantity,
@PathVariable Long id){
return new OrderedDTO(orderedService.updateOrder(id, quantity));
}
@DeleteMapping("/{id}")
public OrderedDTO deleteOrdered(@PathVariable Long id){
return new OrderedDTO(orderedService.deleteOrder(id));
}
@DeleteMapping()
public void deleteAllOrdereds(){
orderedService.deleteAllOrders();
}
}

View File

@ -0,0 +1,52 @@
package com.example.ipLab.StoreDataBase.Controllers;
import com.example.ipLab.StoreDataBase.DTO.ProductDTO;
import com.example.ipLab.StoreDataBase.Model.Product;
import com.example.ipLab.StoreDataBase.Service.ProductService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/product")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService){
this.productService = productService;
}
@GetMapping("/{id}")
public ProductDTO getProduct(@PathVariable Long id){
return new ProductDTO(productService.getProduct(id));
}
@GetMapping
public List<ProductDTO> getProducts(){
return productService.getAllProducts().stream()
.map(ProductDTO::new)
.toList();
}
@PostMapping
public ProductDTO createProduct(@RequestParam("productName") String productName){
final Product product = productService.addProduct(productName);
return new ProductDTO(product);
}
@PutMapping("/{id}")
public ProductDTO updateProduct(@RequestParam("productName") String productName,
@PathVariable Long id){
return new ProductDTO(productService.updateProduct(id, productName));
}
@DeleteMapping("/{id}")
public ProductDTO deleteProduct(@PathVariable Long id){
return new ProductDTO(productService.deleteProduct(id));
}
@DeleteMapping()
public void deleteAllProducts(){
productService.deleteAllProducts();
}
}

View File

@ -0,0 +1,62 @@
package com.example.ipLab.StoreDataBase.Controllers;
import com.example.ipLab.StoreDataBase.DTO.CustomerDTO;
import com.example.ipLab.StoreDataBase.DTO.ProductDTO;
import com.example.ipLab.StoreDataBase.DTO.StoreDTO;
import com.example.ipLab.StoreDataBase.Model.Customer;
import com.example.ipLab.StoreDataBase.Model.Store;
import com.example.ipLab.StoreDataBase.Service.CustomerService;
import com.example.ipLab.StoreDataBase.Service.StoreService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/store")
public class StoreController {
private final StoreService storeService;
public StoreController(StoreService storeService){
this.storeService = storeService;
}
@GetMapping("/{id}")
public StoreDTO getStore(@PathVariable Long id){
return new StoreDTO(storeService.getStore(id));
}
@GetMapping
public List<StoreDTO> getStores(){
return storeService.getAllStores().stream()
.map(StoreDTO::new)
.toList();
}
@PostMapping
public StoreDTO createStore(@RequestParam("storeName") String storeName){
final Store store = storeService.addStore(storeName);
return new StoreDTO(store);
}
@PutMapping("/{id}")
public StoreDTO updateStore(@RequestParam("storeName") String storeName,
@PathVariable Long id){
return new StoreDTO(storeService.updateStore(id, storeName));
}
@PutMapping("/{storeId}-{productId}")
public ProductDTO addProduct(@PathVariable Long storeId,
@PathVariable Long productId){
return new ProductDTO(storeService.addProduct(storeId, productId));
}
@DeleteMapping("/{id}")
public StoreDTO deleteStore(@PathVariable Long id){
return new StoreDTO(storeService.deleteStore(id));
}
@DeleteMapping()
public void deleteAllStores(){
storeService.deleteAllStores();
}
}

View File

@ -0,0 +1,41 @@
package com.example.ipLab.StoreDataBase.DTO;
import com.example.ipLab.StoreDataBase.Model.Customer;
import java.util.List;
public class CustomerDTO {
public final Long id;
public final String lastname;
public final String firstname;
public final String middleName;
public final List<OrderedDTO> orders;
public CustomerDTO(Customer customer){
this.id = customer.getId();
this.lastname = customer.getLastName();
this.firstname = customer.getFirstName();
this.middleName = customer.getMiddleName();
this.orders = customer.getOrders().stream().map(OrderedDTO::new).toList();
}
public Long getId() {
return id;
}
public String getLastname() {
return lastname;
}
public String getFirstname() {
return firstname;
}
public String getMiddleName() {
return middleName;
}
public List<OrderedDTO> getOrders() {
return orders;
}
}

View File

@ -0,0 +1,33 @@
package com.example.ipLab.StoreDataBase.DTO;
import com.example.ipLab.StoreDataBase.Model.Ordered;
public class OrderedDTO {
public final Long id;
public final int quantity;
public final ProductDTO product;
public final CustomerDTO customer;
public OrderedDTO(Ordered ordered){
this.id = ordered.getId();
this.quantity = ordered.getQuantity();
this.product = new ProductDTO(ordered.getProduct());
this.customer = new CustomerDTO(ordered.getCustomer());
}
public Long getId() {
return id;
}
public int getQuantity() {
return quantity;
}
public ProductDTO getProduct() {
return product;
}
public CustomerDTO getCustomer() {
return customer;
}
}

View File

@ -0,0 +1,35 @@
package com.example.ipLab.StoreDataBase.DTO;
import com.example.ipLab.StoreDataBase.Model.Product;
import java.util.List;
public class ProductDTO {
public final Long id;
public final String name;
public final StoreDTO store;
public final List<OrderedDTO> orders;
public ProductDTO(Product product){
this.id = product.getId();
this.name = product.getName();
this.store = new StoreDTO(product.getStore());
this.orders = product.getOrders().stream().map(OrderedDTO::new).toList();
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public StoreDTO getStore() {
return store;
}
public List<OrderedDTO> getOrders() {
return orders;
}
}

View File

@ -0,0 +1,29 @@
package com.example.ipLab.StoreDataBase.DTO;
import com.example.ipLab.StoreDataBase.Model.Store;
import java.util.List;
public class StoreDTO {
public final Long id;
public final String storeName;
public final List<ProductDTO> products;
public StoreDTO(Store store){
this.id = store.getId();
this.storeName = store.getStoreName();
this.products = store.getProducts().stream().map(ProductDTO::new).toList();
}
public Long getId() {
return id;
}
public String getStoreName() {
return storeName;
}
public List<ProductDTO> getProducts() {
return products;
}
}

View File

@ -0,0 +1,7 @@
package com.example.ipLab.StoreDataBase.Exceptions;
public class CustomerNotFoundException extends RuntimeException{
public CustomerNotFoundException(Long id){
super(String.format("Customer with id: %s hasn't been found", id));
}
}

View File

@ -0,0 +1,7 @@
package com.example.ipLab.StoreDataBase.Exceptions;
public class OrderedNotFoundException extends RuntimeException{
public OrderedNotFoundException(Long id){
super(String.format("Order with id: %s hasn't been found", id));
}
}

View File

@ -0,0 +1,7 @@
package com.example.ipLab.StoreDataBase.Exceptions;
public class ProductNotFoundException extends RuntimeException{
public ProductNotFoundException(Long id){
super(String.format("Product with id: %s hasn't been found", id));
}
}

View File

@ -0,0 +1,7 @@
package com.example.ipLab.StoreDataBase.Exceptions;
public class StoreNotFoundException extends RuntimeException{
public StoreNotFoundException(Long id){
super(String.format("Store with id: %s hasn't been found", id));
}
}

View File

@ -1,6 +1,7 @@
package com.example.ipLab.StoreDataBase.Model; package com.example.ipLab.StoreDataBase.Model;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -12,10 +13,13 @@ public class Customer {
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@Column @Column
@NotBlank(message = "Customer's last name can't be empty")
private String lastName; private String lastName;
@Column @Column
@NotBlank(message = "Customer's first name can't be empty")
private String firstName; private String firstName;
@Column @Column
@NotBlank(message = "Customer's middle name can't be empty")
private String middleName; private String middleName;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL) @OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL)
private List<Ordered> orders; private List<Ordered> orders;

View File

@ -9,9 +9,6 @@ public class Ordered {
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="store_fk")
private Store store;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="customer_fk") @JoinColumn(name="customer_fk")
private Customer customer; private Customer customer;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@ -28,9 +25,6 @@ public class Ordered {
return id; return id;
} }
public Store getStore() {
return store;
}
public Customer getCustomer() { public Customer getCustomer() {
return customer; return customer;
@ -55,13 +49,6 @@ public class Ordered {
this.quantity = quantity; this.quantity = quantity;
} }
public void setStore(Store store) {
this.store = store;
if (!store.getOrders().contains(this)){
store.AddOrdered(this);
}
}
public void setCustomer(Customer customer) { public void setCustomer(Customer customer) {
this.customer = customer; this.customer = customer;
if (!customer.getOrders().contains(this)){ if (!customer.getOrders().contains(this)){

View File

@ -1,6 +1,7 @@
package com.example.ipLab.StoreDataBase.Model; package com.example.ipLab.StoreDataBase.Model;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -12,6 +13,7 @@ public class Product {
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@Column @Column
@NotBlank(message = "Product's name can't be empty")
private String name; private String name;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "store_fk") @JoinColumn(name = "store_fk")

View File

@ -2,6 +2,7 @@ package com.example.ipLab.StoreDataBase.Model;
import com.example.ipLab.StoreDataBase.Service.ProductService; import com.example.ipLab.StoreDataBase.Service.ProductService;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -13,15 +14,13 @@ public class Store {
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@Column @Column
@NotBlank(message = "Store's name can't be empty")
private String storeName; private String storeName;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "store", cascade = CascadeType.ALL, orphanRemoval = true) @OneToMany(fetch = FetchType.EAGER, mappedBy = "store", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Product> products; private List<Product> products;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "store", cascade = CascadeType.ALL)
private List<Ordered> orders;
public Store(){} public Store(){}
public Store(String storeName){ public Store(String storeName){
this.storeName = storeName; this.storeName = storeName;
this.orders = new ArrayList<>();
this.products = new ArrayList<>(); this.products = new ArrayList<>();
} }
@ -33,10 +32,6 @@ public class Store {
return storeName; return storeName;
} }
public List<Ordered> getOrders() {
return orders;
}
public List<Product> getProducts() { public List<Product> getProducts() {
return products; return products;
} }
@ -46,12 +41,6 @@ public class Store {
product.setStore(this); product.setStore(this);
} }
} }
public void AddOrdered(Ordered ordered){
this.orders.add(ordered);
if (ordered.getStore() != this){
ordered.setStore(this);
}
}
public void setStoreName(String storeName) { public void setStoreName(String storeName) {
this.storeName = storeName; this.storeName = storeName;

View File

@ -0,0 +1,7 @@
package com.example.ipLab.StoreDataBase.Repositories;
import com.example.ipLab.StoreDataBase.Model.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

View File

@ -0,0 +1,7 @@
package com.example.ipLab.StoreDataBase.Repositories;
import com.example.ipLab.StoreDataBase.Model.Ordered;
import org.springframework.data.jpa.repository.JpaRepository;
public interface OrderedRepository extends JpaRepository<Ordered, Long> {
}

View File

@ -0,0 +1,7 @@
package com.example.ipLab.StoreDataBase.Repositories;
import com.example.ipLab.StoreDataBase.Model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}

View File

@ -0,0 +1,7 @@
package com.example.ipLab.StoreDataBase.Repositories;
import com.example.ipLab.StoreDataBase.Model.Store;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StoreRepository extends JpaRepository<Store, Long> {
}

View File

@ -1,6 +1,9 @@
package com.example.ipLab.StoreDataBase.Service; package com.example.ipLab.StoreDataBase.Service;
import com.example.ipLab.StoreDataBase.Exceptions.CustomerNotFoundException;
import com.example.ipLab.StoreDataBase.Model.Customer; import com.example.ipLab.StoreDataBase.Model.Customer;
import com.example.ipLab.StoreDataBase.Repositories.CustomerRepository;
import com.example.ipLab.StoreDataBase.util.validation.ValidatorUtil;
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException; import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContext;
@ -12,53 +15,50 @@ import java.util.List;
@Service @Service
public class CustomerService { public class CustomerService {
@PersistenceContext private final CustomerRepository customerRepository;
private EntityManager em; private final ValidatorUtil validatorUtil;
public CustomerService(CustomerRepository customerRepository,
ValidatorUtil validatorUtil){
this.customerRepository = customerRepository;
this.validatorUtil = validatorUtil;
}
@Transactional @Transactional
public Customer addCustomer(String customerLastName, String customerFirstName, String customerMiddleName){ public Customer addCustomer(String customerLastName, String customerFirstName, String customerMiddleName){
if (!StringUtils.hasText(customerLastName) || !StringUtils.hasText(customerFirstName) || !StringUtils.hasText(customerMiddleName)){ Customer customer = new Customer(customerLastName, customerFirstName, customerMiddleName);
throw new IllegalArgumentException("Customer name is null or empty"); validatorUtil.validate(customer);
} return customerRepository.save(customer);
final Customer customer = new Customer(customerLastName, customerFirstName, customerMiddleName);
em.persist(customer);
return customer;
} }
@Transactional() @Transactional()
public Customer getCustomer(Long id){ public Customer getCustomer(Long id){
Customer customer = em.find(Customer.class, id); return customerRepository.findById(id).orElseThrow(() -> new CustomerNotFoundException(id));
if (customer == null){
throw new EntityNotFoundException(String.format("Customer with id = %s isn't found", id));
}
return customer;
} }
@Transactional @Transactional
public List<Customer> getAllCustomers(){ public List<Customer> getAllCustomers(){
return em.createQuery("SELECT c from Customer c", Customer.class).getResultList(); return customerRepository.findAll();
} }
@Transactional @Transactional
public Customer updateCustomer(Long id, String customerLastName, String customerFirstName, String customerMiddleName){ public Customer updateCustomer(Long id, String customerLastName, String customerFirstName, String customerMiddleName){
if (!StringUtils.hasText(customerLastName) || !StringUtils.hasText(customerFirstName) || !StringUtils.hasText(customerMiddleName)){ Customer customer = getCustomer(id);
throw new IllegalArgumentException("Customer name is null or empty");
}
final Customer customer = getCustomer(id);
customer.setLastName(customerLastName); customer.setLastName(customerLastName);
customer.setFirstName(customerFirstName); customer.setFirstName(customerFirstName);
customer.setMiddleName(customerMiddleName); customer.setMiddleName(customerMiddleName);
return em.merge(customer); validatorUtil.validate(customer);
return customerRepository.save(customer);
} }
@Transactional @Transactional
public Customer deleteCustomer(Long id){ public Customer deleteCustomer(Long id){
final Customer customer = getCustomer(id); Customer customer = getCustomer(id);
em.remove(customer); customerRepository.delete(customer);
return customer; return customer;
} }
@Transactional @Transactional
public void deleteAllCustomers(){ public void deleteAllCustomers(){
em.createQuery("delete from Customer"); customerRepository.deleteAll();
} }
} }

View File

@ -1,115 +1,81 @@
package com.example.ipLab.StoreDataBase.Service; package com.example.ipLab.StoreDataBase.Service;
import com.example.ipLab.StoreDataBase.Exceptions.OrderedNotFoundException;
import com.example.ipLab.StoreDataBase.Model.Customer; import com.example.ipLab.StoreDataBase.Model.Customer;
import com.example.ipLab.StoreDataBase.Model.Ordered; import com.example.ipLab.StoreDataBase.Model.Ordered;
import com.example.ipLab.StoreDataBase.Model.Product; import com.example.ipLab.StoreDataBase.Model.Product;
import com.example.ipLab.StoreDataBase.Model.Store; import com.example.ipLab.StoreDataBase.Model.Store;
import com.example.ipLab.StoreDataBase.Repositories.OrderedRepository;
import com.example.ipLab.StoreDataBase.util.validation.ValidatorUtil;
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException; import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.Order;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import org.aspectj.weaver.ast.Or;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List; import java.util.List;
@Service @Service
public class OrderService { public class OrderService {
@PersistenceContext private final OrderedRepository orderedRepository;
private EntityManager em; private final ValidatorUtil validatorUtil;
public OrderService(OrderedRepository orderedRepository,
ValidatorUtil validatorUtil,
ProductService productService){
this.productService = productService;
this.orderedRepository = orderedRepository;
this.validatorUtil = validatorUtil;
}
private ProductService productService; private ProductService productService;
public OrderService(ProductService productService){
this.productService = productService;
}
@Transactional @Transactional
public Ordered addOrder(Store store, Product product, Customer customer, int quantity){ public Ordered addOrder(Product product, Customer customer, int quantity){
final Ordered order = new Ordered(quantity); final Ordered order = new Ordered(quantity);
validatorUtil.validate(order);
product.AddOrdered(order); product.AddOrdered(order);
customer.AddOrdered(order); customer.AddOrdered(order);
store.AddOrdered(order); orderedRepository.save(order);
em.persist(order);
return order; return order;
} }
@Transactional() @Transactional()
public Ordered getOrder(Long id){ public Ordered getOrder(Long id){
Ordered order = em.find(Ordered.class, id); return orderedRepository.findById(id).orElseThrow(() -> new OrderedNotFoundException(id));
if (order == null){
throw new EntityNotFoundException(String.format("Ordered with id = %s isn't found", id));
}
return order;
}
@Transactional
public List<Ordered> getOrdersWithProduct(Long productId, int minQuantity, int maxQuantity){
return em.createQuery("SELECT o FROM Ordered o WHERE o.product.id = ?1 AND o.quantity >= ?2 AND o.quantity <= ?3",Ordered.class)
.setParameter(1, productId)
.setParameter(2, minQuantity)
.setParameter(3, maxQuantity)
.getResultList();
} }
@Transactional @Transactional
public List<Ordered> getAllOrders(){ public List<Ordered> getAllOrders(){
return em.createQuery("SELECT o FROM Ordered o", Ordered.class).getResultList(); return orderedRepository.findAll();
} }
@Transactional @Transactional
public Ordered updateOrder(Long id, int quantity){ public Ordered updateOrder(Long id, int quantity){
final Ordered order = getOrder(id); final Ordered order = getOrder(id);
order.setQuantity(quantity); order.setQuantity(quantity);
return em.merge(order); validatorUtil.validate(order);
return orderedRepository.save(order);
} }
@Transactional @Transactional
public Ordered deleteOrder(Long id){ public Ordered deleteOrder(Long id){
final Ordered order = getOrder(id); final Ordered order = getOrder(id);
order.getStore().getOrders().remove(order);
order.getCustomer().getOrders().remove(order); order.getCustomer().getOrders().remove(order);
em.remove(order); orderedRepository.delete(order);
return order; return order;
} }
@Transactional @Transactional
public void deleteAllOrders(){ public void deleteAllOrders(){
em.createQuery("delete from Ordered").executeUpdate(); orderedRepository.deleteAll();
} }
//product section //product section
@Transactional() @Transactional()
public Product getProduct(Long productId, Long orderId){ public Product getProduct(Long orderId){
Ordered order = em.find(Ordered.class, orderId); Ordered order = getOrder(orderId);
if (order != null) {
return order.getProduct(); return order.getProduct();
} }
else throw new EntityNotFoundException(String.format("Product with id = %s isn't found", productId));
}
@Transactional
public Product updateProduct(Long orderId, Long productId, String productName){
if (!StringUtils.hasText(productName)){
throw new IllegalArgumentException("Product name is null or empty");
}
final Product product = getProduct(productId, orderId);
if (product == null){
throw new EntityNotFoundException(String.format("Product with id = %s isn't found", productId));
}
product.setName(productName);
return em.merge(product);
}
@Transactional
public Product deleteProduct(Long orderId, Long productId){
final Product product = getProduct(productId, orderId);
if (product == null){
throw new EntityNotFoundException(String.format("Product with id = %s isn't found", productId));
}
var order = product.getOrders().stream().filter(or -> or.getId() == orderId).findFirst();
if (order.isPresent()) order.get().setProduct(null);
else throw new EntityNotFoundException(String.format("Order with id = %s isn't found", orderId));
return product;
}
} }

View File

@ -1,9 +1,12 @@
package com.example.ipLab.StoreDataBase.Service; package com.example.ipLab.StoreDataBase.Service;
import com.example.ipLab.StoreDataBase.Exceptions.ProductNotFoundException;
import com.example.ipLab.StoreDataBase.Model.Customer; import com.example.ipLab.StoreDataBase.Model.Customer;
import com.example.ipLab.StoreDataBase.Model.Ordered; import com.example.ipLab.StoreDataBase.Model.Ordered;
import com.example.ipLab.StoreDataBase.Model.Product; import com.example.ipLab.StoreDataBase.Model.Product;
import com.example.ipLab.StoreDataBase.Model.Store; import com.example.ipLab.StoreDataBase.Model.Store;
import com.example.ipLab.StoreDataBase.Repositories.ProductRepository;
import com.example.ipLab.StoreDataBase.util.validation.ValidatorUtil;
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException; import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContext;
@ -14,59 +17,49 @@ import org.springframework.util.StringUtils;
import java.util.List; import java.util.List;
@Service @Service
public class ProductService { public class ProductService {
@PersistenceContext private final ProductRepository productRepository;
private EntityManager em; private final ValidatorUtil validatorUtil;
public ProductService(ProductRepository productRepository, ValidatorUtil validatorUtil){
this.productRepository = productRepository;
this.validatorUtil = validatorUtil;
}
@Transactional @Transactional
public Product addProduct(String productName){ public Product addProduct(String productName){
if (!StringUtils.hasText(productName)){
throw new IllegalArgumentException("Product name is null or empty");
}
final Product product = new Product(productName); final Product product = new Product(productName);
em.persist(product); validatorUtil.validate(product);
productRepository.save(product);
return product; return product;
} }
@Transactional() @Transactional()
public Product getProduct(Long id){ public Product getProduct(Long id){
Product product = em.find(Product.class, id); return productRepository.findById(id).orElseThrow(() -> new ProductNotFoundException(id));
if (product == null){
throw new EntityNotFoundException(String.format("Product with id = %s isn't found", id));
}
em.persist(product);
return product;
} }
@Transactional @Transactional
public List<Product> getAllProducts(){ public List<Product> getAllProducts(){
return em.createQuery("SELECT p FROM Product p", Product.class).getResultList(); return productRepository.findAll();
} }
@Transactional @Transactional
public Product updateProduct(Long id, String productName){ public Product updateProduct(Long id, String productName){
if (!StringUtils.hasText(productName)){
throw new IllegalArgumentException("Product name is null or empty");
}
final Product product = getProduct(id); final Product product = getProduct(id);
if (product == null){
throw new EntityNotFoundException(String.format("Product with id = %s isn't found", id));
}
product.setName(productName); product.setName(productName);
return em.merge(product); validatorUtil.validate(product);
return productRepository.save(product);
} }
@Transactional @Transactional
public Product deleteProduct(Long id){ public Product deleteProduct(Long id){
final Product product = getProduct(id); final Product product = getProduct(id);
if (product == null){
throw new EntityNotFoundException(String.format("Product with id = %s isn't found", id));
}
Store store = product.getStore(); Store store = product.getStore();
if (store != null) store.getProducts().remove(product); if (store != null) store.getProducts().remove(product);
em.remove(product); productRepository.delete(product);
return product; return product;
} }
@Transactional @Transactional
public void deleteAllProducts(){ public void deleteAllProducts(){
em.createQuery("delete from Product"); productRepository.deleteAll();
} }
} }

View File

@ -1,7 +1,10 @@
package com.example.ipLab.StoreDataBase.Service; package com.example.ipLab.StoreDataBase.Service;
import com.example.ipLab.StoreDataBase.Exceptions.StoreNotFoundException;
import com.example.ipLab.StoreDataBase.Model.Product; import com.example.ipLab.StoreDataBase.Model.Product;
import com.example.ipLab.StoreDataBase.Model.Store; import com.example.ipLab.StoreDataBase.Model.Store;
import com.example.ipLab.StoreDataBase.Repositories.StoreRepository;
import com.example.ipLab.StoreDataBase.util.validation.ValidatorUtil;
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException; import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContext;
@ -14,57 +17,51 @@ import java.util.List;
@Service @Service
public class StoreService { public class StoreService {
@PersistenceContext private final StoreRepository storeRepository;
private EntityManager em; private final ValidatorUtil validatorUtil;
private ProductService productService; private ProductService productService;
public StoreService(ProductService productService){ public StoreService(StoreRepository storeRepository, ValidatorUtil validatorUtil, ProductService productService){
this.storeRepository = storeRepository;
this.validatorUtil = validatorUtil;
this.productService = productService; this.productService = productService;
} }
@Transactional @Transactional
public Store addStore(String storeName){ public Store addStore(String storeName){
if (!StringUtils.hasText(storeName)){
throw new IllegalArgumentException("Store name is null or empty");
}
final Store store = new Store(storeName); final Store store = new Store(storeName);
em.persist(store); validatorUtil.validate(store);
storeRepository.save(store);
return store; return store;
} }
@Transactional() @Transactional()
public Store getStore(Long id){ public Store getStore(Long id){
Store store = em.find(Store.class, id); return storeRepository.findById(id).orElseThrow(() -> new StoreNotFoundException(id));
if (store == null){
throw new EntityNotFoundException(String.format("Store with id = %s isn't found", id));
}
return store;
} }
@Transactional @Transactional
public List<Store> getAllStores(){ public List<Store> getAllStores(){
return em.createQuery("SELECT s FROM Store s", Store.class).getResultList(); return storeRepository.findAll();
} }
@Transactional @Transactional
public Store updateStore(Long id, String storeName){ public Store updateStore(Long id, String storeName){
if (!StringUtils.hasText(storeName)){
throw new IllegalArgumentException("Store name is null or empty");
}
final Store store = getStore(id); final Store store = getStore(id);
store.setStoreName(storeName); store.setStoreName(storeName);
return em.merge(store); validatorUtil.validate(store);
return storeRepository.save(store);
} }
@Transactional @Transactional
public Store deleteStore(Long id){ public Store deleteStore(Long id){
final Store store = getStore(id); final Store store = getStore(id);
em.remove(store); storeRepository.delete(store);
return store; return store;
} }
@Transactional @Transactional
public void deleteAllStores(){ public void deleteAllStores(){
em.createQuery("delete from Store"); storeRepository.deleteAll();
} }
//product section //product section
@ -73,7 +70,7 @@ public class StoreService {
Store store = getStore(storeId); Store store = getStore(storeId);
Product product = productService.getProduct(productId); Product product = productService.getProduct(productId);
store.AddProduct(product); store.AddProduct(product);
em.persist(store); storeRepository.save(store);
return product; return product;
} }
@ -98,7 +95,7 @@ public class StoreService {
Store store = getStore(storeId); Store store = getStore(storeId);
Product product = getProductFromStore(productId, storeId); Product product = getProductFromStore(productId, storeId);
store.getProducts().remove(product); store.getProducts().remove(product);
em.remove(product); product.setStore(null);
return product; return product;
} }
@Transactional @Transactional
@ -109,7 +106,6 @@ public class StoreService {
storeProducts) { storeProducts) {
pr.setStore(null); pr.setStore(null);
store.getProducts().remove(pr); store.getProducts().remove(pr);
em.remove(pr);
} }
} }
} }

View File

@ -0,0 +1,42 @@
package com.example.ipLab.StoreDataBase.util.error;
import com.example.ipLab.StoreDataBase.Exceptions.CustomerNotFoundException;
import com.example.ipLab.StoreDataBase.Exceptions.OrderedNotFoundException;
import com.example.ipLab.StoreDataBase.Exceptions.ProductNotFoundException;
import com.example.ipLab.StoreDataBase.Exceptions.StoreNotFoundException;
import com.example.ipLab.StoreDataBase.util.validation.ValidationException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController {
@ExceptionHandler({
CustomerNotFoundException.class,
OrderedNotFoundException.class,
ProductNotFoundException.class,
StoreNotFoundException.class
})
public ResponseEntity<Object> handleException(Throwable e){
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -0,0 +1,9 @@
package com.example.ipLab.StoreDataBase.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException{
public ValidationException(Set<String> errors){
super(String.join("\n", errors));
}
}

View File

@ -0,0 +1,30 @@
package com.example.ipLab.StoreDataBase.util.validation;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil {
private final Validator validator;
public ValidatorUtil(){
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()){
this.validator = factory.getValidator();
}
}
public <T> void validate(T object) {
final Set<ConstraintViolation<T>> errors = validator.validate(object);
if (!errors.isEmpty()) {
throw new ValidationException(errors.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toSet()));
}
}
}

View File

@ -1,23 +0,0 @@
package com.example.ipLab.TypesCalc.Configuration;
import com.example.ipLab.TypesCalc.domen.TypeCalcInteger;
import com.example.ipLab.TypesCalc.domen.TypeCalcString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CalcConfiguration {
private final Logger log = LoggerFactory.getLogger(CalcConfiguration.class);
@Bean(value="int")
public TypeCalcInteger createTypeCalcInteger(){
return new TypeCalcInteger();
}
@Bean(value="string")
public TypeCalcString createTypeCalcString(){
return new TypeCalcString();
}
}

View File

@ -1,33 +0,0 @@
package com.example.ipLab.TypesCalc.Service;
import com.example.ipLab.TypesCalc.domen.TypeCalc;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
@Service
public class CalcService {
private final ApplicationContext applicationContext;
public CalcService(ApplicationContext applicationContext){this.applicationContext = applicationContext;}
public Object Sum(Object obj1, Object obj2, String type){
final TypeCalc typeCalculator = (TypeCalc) applicationContext.getBean(type);
if (type.startsWith("int")) return typeCalculator.Sum(Integer.parseInt(obj1.toString()), Integer.parseInt(obj2.toString()));
return typeCalculator.Sum(obj1, obj2);
}
public Object Dif(Object obj1, Object obj2, String type){
final TypeCalc typeCalculator = (TypeCalc) applicationContext.getBean(type);
if (type.startsWith("int")) return typeCalculator.Dif(Integer.parseInt(obj1.toString()), Integer.parseInt(obj2.toString()));
return typeCalculator.Dif(obj1, obj2);
}
public Object Multiply(Object obj1, Object obj2, String type){
final TypeCalc typeCalculator = (TypeCalc) applicationContext.getBean(type);
if (type.startsWith("int")) return typeCalculator.Multiply(Integer.parseInt(obj1.toString()), Integer.parseInt(obj2.toString()));
return typeCalculator.Multiply(obj1, obj2);
}
public Object Div(Object obj1, Object obj2, String type){
final TypeCalc typeCalculator = (TypeCalc) applicationContext.getBean(type);
if (type.startsWith("int")) return typeCalculator.Div(Integer.parseInt(obj1.toString()), Integer.parseInt(obj2.toString()));
return typeCalculator.Div(obj1, obj2);
}
}

View File

@ -1,41 +0,0 @@
package com.example.ipLab.TypesCalc.controller;
import com.example.ipLab.TypesCalc.Service.CalcService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TypeCalcController {
private final CalcService calcService;
public TypeCalcController(CalcService calcService) {this.calcService = calcService;}
@GetMapping("/CalcSum")
public Object calcSum(@RequestParam(value = "obj1", defaultValue = "null objects") Object obj1,
@RequestParam(value = "obj2", defaultValue = "provided") Object obj2,
@RequestParam(value = "type", defaultValue = "string") String type){
return calcService.Sum(obj1, obj2, type);
}
@GetMapping("/CalcDif")
public Object calcDif(@RequestParam(value = "obj1", defaultValue = "null objects") Object obj1,
@RequestParam(value = "obj2", defaultValue = "provided") Object obj2,
@RequestParam(value = "type", defaultValue = "string") String type){
return calcService.Dif(obj1, obj2, type);
}
@GetMapping("/CalcMultiply")
public Object calcMultiply(@RequestParam(value = "obj1", defaultValue = "null objects") Object obj1,
@RequestParam(value = "obj2", defaultValue = "provided") Object obj2,
@RequestParam(value = "type", defaultValue = "string") String type){
return calcService.Multiply(obj1, obj2, type);
}
@GetMapping("/CalcDiv")
public Object calcDiv(@RequestParam(value = "obj1", defaultValue = "null objects") Object obj1,
@RequestParam(value = "obj2", defaultValue = "provided") Object obj2,
@RequestParam(value = "type", defaultValue = "string") String type){
return calcService.Div(obj1, obj2, type);
}
}

View File

@ -1,8 +0,0 @@
package com.example.ipLab.TypesCalc.domen;
public interface TypeCalc<T> {
T Sum(T obj1, T obj2);
T Dif(T obj1, T obj2);
T Multiply(T obj1, T obj2);
T Div(T obj1, T obj2);
}

View File

@ -1,30 +0,0 @@
package com.example.ipLab.TypesCalc.domen;
import org.springframework.stereotype.Component;
public class TypeCalcInteger implements TypeCalc<Integer>{
@Override
public Integer Sum(Integer num1, Integer num2) {
return num1 + num2;
}
@Override
public Integer Dif(Integer num1, Integer num2) {
return num1 - num2;
}
@Override
public Integer Multiply(Integer num1, Integer num2) {
return num1 * num2;
}
@Override
public Integer Div(Integer num1, Integer num2) {
try {
return num1 / num2;
}
catch (ArithmeticException ex){
return 0;
}
}
}

View File

@ -1,57 +0,0 @@
package com.example.ipLab.TypesCalc.domen;
import org.springframework.stereotype.Component;
public class TypeCalcString implements TypeCalc<String> {
@Override
public String Sum(String s1, String s2) {
return s1 + s2;
}
@Override
public String Dif(String s1, String s2) {
String res = "";
for (char c : s1.toCharArray()){
boolean foundInOther = false;
for (int i = 0; i < s2.length(); i++){
if (c == s2.charAt(i)) {
foundInOther = true;
break;
}
}
if (!foundInOther) res += c;
}
return res;
}
@Override
public String Multiply(String s1, String s2) {
String res = "";
for (char c : s1.toCharArray()){
boolean foundInOther = false;
for (int i = 0; i < s2.length(); i++){
if (c == s2.charAt(i)) {
foundInOther = true;
break;
}
}
if (foundInOther) res += c;
}
return res;
}
@Override
public String Div(String s1, String s2) {
StringBuilder res = new StringBuilder();
int maxLength = Integer.max(s1.length(), s2.length());
for (int i = 0; i < maxLength; i++){
if (i < s1.length()){
res.append(s1.charAt(i));
}
if (i < s2.length()){
res.append(s2.charAt(i));
}
}
return res.toString();
}
}

View File

@ -1,39 +0,0 @@
package com.example.ipLab.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CalcController {
@GetMapping("/second")
public int second(@RequestParam(value = "num") int num){
return num*num;
}
@GetMapping("/root")
public double root(@RequestParam(value = "num") int num){
return Math.sqrt(num);
}
@GetMapping("/fact")
public int fact(@RequestParam(value = "num") int num){
int res = 1;
for (int i = 2; i <= num; i++) {
res *= i;
}
return res;
}
@GetMapping("/digit")
public int digit(@RequestParam(value = "num") int num){
if (num < 0) num *= -1;
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
}