Четвертая лабораторная работа. Созданы DTO, репозитории,ошибки, переделана часть сервисов.

This commit is contained in:
ksenianeva 2023-05-16 09:31:49 +04:00
parent fd9b52de8a
commit 807957816b
27 changed files with 436 additions and 102 deletions

View File

@ -0,0 +1,19 @@
package com.example.lab.DataBase.DTOs;
import java.util.List;
import com.example.lab.DataBase.Models.Cart;
public class CartDTO {
public Long id;;
public CartDTO(Cart cart){
this.id = cart.getId();
}
public Long getId() {
return id;
}
public void setId(Long id){
this.id = id;
}
}

View File

@ -0,0 +1,30 @@
package com.example.lab.DataBase.DTOs;
import com.example.lab.DataBase.Models.CountProduct;
import jakarta.persistence.Column;
public class CountProductDTO {
private Long id;
public Integer amount;
public CountProductDTO(CountProduct countProduct){
this.id = countProduct.getId();
this.amount = countProduct.getAmount();
}
public Long getId() {
return id;
}
public void setId(Long id){
this.id = id;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount){
this.amount = amount;
}
}

View File

@ -0,0 +1,49 @@
package com.example.lab.DataBase.DTOs;
import com.example.lab.DataBase.Models.Customer;
import jakarta.persistence.Column;
public class CustomerDTO {
public Long id;
public String firstName;
public String lastName;
public String customerAddress;
public CustomerDTO(Customer customer){
this.id = customer.getId();
this.lastName = customer.getLastName();
this.firstName = customer.getFirstName();
this.customerAddress = customer.getCustomerAddress();
}
public Long getId(){
return id;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public String getCustomerAddress(){
return customerAddress;
}
public void setId(Long id){
this.id = id;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setCustomerAddress(String customerAddress){
this.customerAddress = customerAddress;
}
}

View File

@ -0,0 +1,29 @@
package com.example.lab.DataBase.DTOs;
import com.example.lab.DataBase.Models.Product;
import com.example.lab.DataBase.Models.ProductCategory;
public class ProductCategoryDTO {
public Long id;
public String name;
public ProductCategoryDTO(ProductCategory productCategory){
this.id = productCategory.getId();
this.name = productCategory.getName();
}
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;
}
}

View File

@ -0,0 +1,38 @@
package com.example.lab.DataBase.DTOs;
import com.example.lab.DataBase.Models.Product;
public class ProductDTO {
public Long id;
public String name;
public float price;
public ProductDTO(Product product){
this.id = product.getId();
this.name = product.getName();
this.price = product.getPrice();
}
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 float getPrice() {
return price;
}
public void setPrice(float price){
this.price = price;
}
}

View File

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

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Exceptions;
public class CountProductNotFoundException extends RuntimeException{
public CountProductNotFoundException(int count){
super(String.format("Product with count: %s hasn't been found", count));
}
}

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.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.lab.DataBase.Exceptions;
public class ProductCategoryNotFoundException extends RuntimeException{
public ProductCategoryNotFoundException(Long id){
super(String.format("Product category with id: %s hasn't been found", id));
}
}

View File

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

View File

@ -1,5 +1,6 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.*;
@ -10,6 +11,7 @@ public class CountProduct {
private Long id;
@Column
@NotBlank(message = "Amount can't be empty, only 0")
private Integer amount;
@ManyToOne(fetch = FetchType.EAGER)
@ -37,6 +39,14 @@ public class CountProduct {
}
}
public Long getId() {
return id;
}
public void setId(Long id){
this.id = id;
}
public Cart getCart() {
return cart;
}

View File

@ -1,6 +1,8 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.Objects;
@Entity
@ -9,10 +11,13 @@ public class Customer {
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotBlank(message = "Customer's first name can't be empty")
private String firstName;
@Column
@NotBlank(message = "Customer's last name can't be empty")
private String lastName;
@Column
@NotBlank(message = "Customer's address can't be empty")
private String customerAddress;
@OneToOne(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL)

View File

@ -1,6 +1,7 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
@ -11,7 +12,12 @@ public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotBlank(message = "Product's name can't be empty")
private String name;
@Column
@NotBlank(message = "Price can't be empty")
private float price;
@OneToMany

View File

@ -1,6 +1,8 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.*;
@Entity
@ -8,6 +10,8 @@ public class ProductCategory {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotBlank(message = "Product category name can't be empty")
private String name;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "productCategory", cascade = CascadeType.ALL)
private List<Product> products;

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Repositories;
import com.example.lab.DataBase.Models.Cart;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CartRepository extends JpaRepository<Cart, Long> {
}

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Repositories;
import com.example.lab.DataBase.Models.CountProduct;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CountProductRepository extends JpaRepository<CountProduct, Integer> {
}

View File

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

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Repositories;
import com.example.lab.DataBase.Models.ProductCategory;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Long> {
}

View File

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

View File

@ -1,61 +1,61 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Exceptions.CustomerNotFoundException;
import com.example.lab.DataBase.Models.Customer;
import com.example.lab.DataBase.Models.Product;
import com.example.lab.DataBase.Repositories.CustomerRepository;
import jakarta.persistence.*;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.example.lab.DataBase.Models.Cart;
import com.example.lab.DataBase.Repositories.CartRepository;
import com.example.lab.DataBase.Exceptions.CartNotFoundException;
import com.example.lab.DataBase.util.Validation.ValidatorUtil;
import com.example.lab.DataBase.util.Validation.ValidationException;
import java.util.List;
@Service
public class CartService {
@PersistenceContext
private EntityManager em;
private final ProductService productService;
private final CountProductService countProductService;
private final CartRepository cartRepository;
private final ValidatorUtil validatorUtil;
public CartService(ProductService productService, CountProductService countProductService){
public CartService(ProductService productService, CountProductService countProductService,
CartRepository cartRepository, ValidatorUtil validatorUtil){
this.productService = productService;
this.countProductService = countProductService;
this.cartRepository = cartRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Cart addCart(Customer customer){
Cart cart = new Cart(customer);
cart.getCustomer().setCart(cart);
em.persist(cart);
return cart;
validatorUtil.validate(cart);
return cartRepository.save(cart);
}
@Transactional()
public Cart getCart(Long id){
Cart cart = em.find(Cart.class, id);
if (cart == null){
throw new EntityNotFoundException(String.format("Error: Cart id %s not found", id));
}
return cart;
return cartRepository.findById(id).orElseThrow(() -> new CartNotFoundException(id));
}
@Transactional
public List<Cart> getAllCarts(){
return em.createQuery("from Cart", Cart.class).getResultList();
return cartRepository.findAll();
}
@Transactional
public Cart deleteCart(Long id){
final Cart cart = getCart(id);
em.remove(cart);
Cart cart = getCart(id);
cartRepository.delete(cart);
return cart;
}
@Transactional
public void deleteAllCarts(){
for (var cart:
getAllCarts()) {
cart.deleteThis();
em.remove(cart);
}
cartRepository.deleteAll();
}
@Transactional

View File

@ -1,7 +1,9 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Exceptions.CustomerNotFoundException;
import com.example.lab.DataBase.Models.*;
import jakarta.persistence.*;
import com.example.lab.DataBase.Repositories.CountProductRepository;
import com.example.lab.DataBase.util.Validation.ValidatorUtil;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.example.lab.DataBase.Models.Product;
@ -10,24 +12,26 @@ import java.util.List;
@Service
public class CountProductService {
@PersistenceContext
private EntityManager em;
private final CountProductRepository countProductRepository;
private final ValidatorUtil validatorUtil;
public CountProductService(CountProductRepository countProductRepository,
ValidatorUtil validatorUtil){
this.countProductRepository= countProductRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public CountProduct addCountProduct(Product product,
Cart cart){
CountProduct countProduct = new CountProduct(cart, product);
em.persist(countProduct);
return countProduct;
validatorUtil.validate(countProduct);
return countProductRepository.save(countProduct);
}
@Transactional
public CountProduct getCountProduct(long productId, long cartId){
var count = getAllCountProducts();
var countProduct = count.stream().filter(x -> x.getProduct().getId() == productId
&& x.getCart().getId() == cartId ).findFirst();
if(countProduct.isEmpty()) return null;
else return countProduct.get();
return countProductRepository.findById(productId, cartId).orElseThrow(() -> new CustomerNotFoundException(id));
}
@Transactional
@ -46,23 +50,18 @@ public class CountProductService {
@Transactional
public CountProduct deleteCountProduct(long productId, long cartId){
final CountProduct countProduct = getCountProduct(productId, cartId);
em.remove(countProduct);
CountProduct countProduct = getCountProduct(productId,cartId);
countProductRepository.delete(countProduct);
return countProduct;
}
@Transactional
public void deleteAll(){
var list = getAllCountProducts();
for (var cp:
list) {
cp.deleteThis();
em.remove(cp);
}
countProductRepository.deleteAll();
}
@Transactional
public List<CountProduct> getAllCountProducts(){
return em.createQuery("from CountProduct", CountProduct.class).getResultList();
return countProductRepository.findAll();
}
}

View File

@ -1,66 +1,61 @@
package com.example.lab.DataBase.Services;
import jakarta.persistence.*;
import com.example.lab.DataBase.Exceptions.CustomerNotFoundException;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.example.lab.DataBase.Models.Customer;
import com.example.lab.DataBase.Repositories.CustomerRepository;
import com.example.lab.DataBase.Exceptions.CustomerNotFoundException;
import com.example.lab.DataBase.util.Validation.ValidatorUtil;
import com.example.lab.DataBase.util.Validation.ValidationException;
import java.util.List;
@Service
public class CustomerService {
@PersistenceContext
private EntityManager em;
private final CustomerRepository customerRepository;
private final ValidatorUtil validatorUtil;
public CustomerService(CustomerRepository customerRepository,
ValidatorUtil validatorUtil){
this.customerRepository = customerRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Customer addCustomer(String customerFirstName, String customerLastName, String customerAddress){
if (!StringUtils.hasText(customerFirstName) || !StringUtils.hasText(customerLastName)){
throw new IllegalArgumentException("Customer first and last names can't be null");
}
else if(!StringUtils.hasText(customerAddress)){
throw new IllegalArgumentException("Customer address can't be null");
}
Customer customer = new Customer(customerLastName, customerFirstName, customerAddress);
em.persist(customer);
return customer;
validatorUtil.validate(customer);
return customerRepository.save(customer);
}
@Transactional()
public Customer getCustomer(Long id){
Customer customer = em.find(Customer.class, id);
if (customer == null){
throw new EntityNotFoundException(String.format("Error: Customer id %s not found", id));
}
return customer;
return customerRepository.findById(id).orElseThrow(() -> new CustomerNotFoundException(id));
}
@Transactional
public List<Customer> getAllCustomers(){
return em.createQuery("get c from Customer c", Customer.class).getResultList();
return customerRepository.findAll();
}
@Transactional
public Customer updateCustomer(Long id, String customerLastName, String customerFirstName, String customerAddress){
if (!StringUtils.hasText(customerLastName) || !StringUtils.hasText(customerFirstName)){
throw new IllegalArgumentException("Customer last or/and first name is null");
}
if (!StringUtils.hasText(customerAddress)){
throw new IllegalArgumentException("Customer address can't be null");
}
final Customer customer = getCustomer(id);
customer.setLastName(customerLastName);
customer.setFirstName(customerFirstName);
customer.setCustomerAddress(customerAddress);
return em.merge(customer);
validatorUtil.validate(customer);
return customerRepository.save(customer);
}
@Transactional
public Customer deleteCustomer(Long id){
final Customer customer = getCustomer(id);
em.remove(customer);
Customer customer = getCustomer(id);
customerRepository.delete(customer);
return customer;
}
@Transactional
public void deleteAllCustomers(){
em.createQuery("Delete from Customer").executeUpdate();
customerRepository.deleteAll();
}
}

View File

@ -1,6 +1,8 @@
package com.example.lab.DataBase.Services;
import jakarta.persistence.*;
import com.example.lab.DataBase.Exceptions.ProductCategoryNotFoundException;
import com.example.lab.DataBase.Repositories.ProductCategoryRepository;
import com.example.lab.DataBase.util.Validation.ValidatorUtil;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@ -9,51 +11,48 @@ import java.util.List;
@Service
public class ProductCategoryService {
@PersistenceContext
private EntityManager em;
private final ProductCategoryRepository productCategoryRepository;
private final ValidatorUtil validatorUtil;
public ProductCategoryService(ProductCategoryRepository productCategoryRepository,
ValidatorUtil validatorUtil){
this.productCategoryRepository = productCategoryRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public ProductCategory addProductCategory(String name){
if (!StringUtils.hasText(name)){
throw new IllegalArgumentException("ProductCategory name can't be null");
}
ProductCategory productCategory = new ProductCategory(name);
em.persist(productCategory);
return productCategory;
validatorUtil.validate(productCategory);
return productCategoryRepository.save(productCategory);
}
@Transactional()
public ProductCategory getProductCategory(Long id){
ProductCategory productCategory = em.find(ProductCategory.class, id);
if (productCategory == null){
throw new EntityNotFoundException(String.format("Error: ProductCategory id %s not found", id));
}
return productCategory;
return productCategoryRepository.findById(id).orElseThrow(() -> new ProductCategoryNotFoundException(id));
}
@Transactional
public List<ProductCategory> getAllProductCategorys(){
return em.createQuery("get c from ProductCategory c", ProductCategory.class).getResultList();
return productCategoryRepository.findAll();
}
@Transactional
public ProductCategory updateProductCategory(Long id, String productCategoryName){
if (!StringUtils.hasText(productCategoryName)){
throw new IllegalArgumentException("ProductCategory name is null");
}
final ProductCategory productCategory = getProductCategory(id);
productCategory.setName(productCategoryName);
return em.merge(productCategory);
validatorUtil.validate(productCategory);
return productCategoryRepository.save(productCategory);
}
@Transactional
public ProductCategory deleteProductCategory(Long id){
final ProductCategory productCategory = getProductCategory(id);
em.remove(productCategory);
productCategoryRepository.delete(productCategory);
return productCategory;
}
@Transactional
public void deleteAllProductCategories(){
em.createQuery("Delete from ProductCategory").executeUpdate();
productCategoryRepository.deleteAll();
}
}

View File

@ -1,7 +1,9 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Exceptions.ProductNotFoundException;
import com.example.lab.DataBase.Models.ProductCategory;
import jakarta.persistence.*;
import com.example.lab.DataBase.Repositories.ProductRepository;
import com.example.lab.DataBase.util.Validation.ValidatorUtil;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@ -10,30 +12,26 @@ import java.util.List;
@Service
public class ProductService {
@PersistenceContext
private EntityManager em;
private final ProductRepository productRepository;
private final ValidatorUtil validatorUtil;
public ProductService(ProductRepository productRepository,
ValidatorUtil validatorUtil){
this.productRepository = productRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Product addProduct(String name, float price, ProductCategory productCategory){
if (!StringUtils.hasText(name)){
throw new IllegalArgumentException("Product first and last names can't be null");
}
else if(price <= 0){
throw new IllegalArgumentException("Product price cant be under 0");
}
Product product = new Product(name, price, productCategory);
product.getProductCategory().AddProduct(product);
em.persist(product);
return product;
validatorUtil.validate(product);
return productRepository.save(product);
}
@Transactional()
public Product getProduct(Long id){
Product product = em.find(Product.class, id);
if (product == null){
throw new EntityNotFoundException(String.format("Error: Product id %s not found", id));
}
return product;
return productRepository.findById(id).orElseThrow(() -> new ProductNotFoundException(id));
}
@Transactional

View File

@ -0,0 +1,44 @@
package com.example.lab.DataBase.util.Error;
import java.util.stream.Collectors;
import com.example.lab.DataBase.Exceptions.CountProductNotFoundException;
import com.example.lab.DataBase.Exceptions.ProductCategoryNotFoundException;
import com.example.lab.DataBase.Exceptions.CustomerNotFoundException;
import com.example.lab.DataBase.Exceptions.ProductNotFoundException;
import com.example.lab.DataBase.Exceptions.CartNotFoundException;
import com.example.lab.DataBase.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;
@ControllerAdvice
public class AdviceController {
@ExceptionHandler({
CustomerNotFoundException.class,
ProductCategoryNotFoundException.class,
ProductNotFoundException.class,
CountProductNotFoundException.class,
CartNotFoundException.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.lab.DataBase.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.lab.DataBase.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()));
}
}
}