Все операции над компонентом работают

This commit is contained in:
Nikita Sergeev 2023-03-16 17:23:50 +04:00
parent a25b5454a7
commit 7ae556be81
10 changed files with 284 additions and 447 deletions

View File

@ -0,0 +1,49 @@
package ip.labwork.student.controller;
import ip.labwork.student.model.Component;
import ip.labwork.student.service.ComponentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/component")
public class ComponentController {
private final ComponentService componentService;
public ComponentController(ComponentService componentService) {
this.componentService = componentService;
}
@GetMapping("/add")
public Component create(@RequestParam("name") String name,
@RequestParam("price") Integer price){
return componentService.addComponent(name, price);
}
@GetMapping("/update")
public Component update(@RequestParam("id") Long id,
@RequestParam("name") String name,
@RequestParam("price") Integer price){
return componentService.updateComponent(id, name, price);
}
@GetMapping("/remove")
public Component remove(@RequestParam("id") Long id){
return componentService.deleteComponent(id);
}
@GetMapping("/removeAll")
public void remove(){
componentService.deleteAllComponent();
}
@GetMapping("/find")
public Component find(@RequestParam("id") Long id){
return componentService.findComponent(id);
}
@GetMapping("/findAll")
public List<Component> findAll(){
return componentService.findAllComponent();
}
}

View File

@ -1,11 +1,10 @@
package ip.labwork.student.model;
import ip.labwork.student.service.ProductService;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
@Entity
public class Component {
@ -13,18 +12,18 @@ public class Component {
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column()
private String ComponentName;
private Integer Count;
@ManyToMany(mappedBy = "components", fetch = FetchType.EAGER)
private List<Product> products;
private String componentName;
private Integer price;
@OneToMany(mappedBy = "component", cascade = CascadeType.ALL)
@JsonIgnore
private Set<ProductComponents> products;
public Component() {
}
public Component(String ComponentName, Integer Count) {
this.ComponentName = ComponentName;
this.Count = Count;
public Component(String componentName, Integer price) {
this.componentName = componentName;
this.price = price;
}
public Long getId() {
@ -32,35 +31,27 @@ public class Component {
}
public String getComponentName() {
return ComponentName;
return componentName;
}
public void setComponentName(String ComponentName) {
this.ComponentName = ComponentName;
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public List<Product> getProduct() {
/*if(products.contains(product)){
return true;
}else{
return false;
}*/
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Set<ProductComponents> getProducts() {
return products;
}
public void setProduct(Product product) {
if (products == null){
products = new ArrayList<>();
}
this.products.add(product);
if (!product.getComponents().contains(this)) { // warning this may cause performance issues if you have a large data set since this operation is O(n)
product.getComponents().add(this);
}
}
public Integer getCount() {
return Count;
}
public void setCount(Integer Count) {
this.Count = Count;
public void setProducts(Set<ProductComponents> products) {
this.products = products;
}
@Override
@ -80,8 +71,8 @@ public class Component {
public String toString() {
return "Component{" +
"id=" + id +
", ComponentName='" + ComponentName + '\'' +
", Count='" + Count + '\'' +
", componentName='" + componentName + '\'' +
", price='" + price + '\'' +
'}';
}
}

View File

@ -1,82 +0,0 @@
package ip.labwork.student.model;
import jakarta.persistence.*;
import java.util.*;
@Entity
@Table(name="tab_order")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Temporal(TemporalType.DATE)
private Date CreateDate;
private Integer Count;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "ords_product",
joinColumns = @JoinColumn(name = "ord_fk"),
inverseJoinColumns = @JoinColumn(name = "product_fk"))
private List<Product> products;
public Order() {
}
public Order(Date CreateDate, Integer Count) {
this.CreateDate = CreateDate;
this.Count = Count;
}
public void addProduct(Product product) {
if (products == null){
products = new ArrayList<>();
}
this.products.add(product);
if (product.getOrder() == null) {
product.setOrder(this);
}
}
public Long getId() {
return id;
}
public Date getCreateDate() {
return CreateDate;
}
public void setCreateDate(Date CreateDate) {
this.CreateDate = CreateDate;
}
public Integer getCount() {
return Count;
}
public void setCount(Integer Count) {
this.Count = Count;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Order ord = (Order) o;
return Objects.equals(id, ord.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Ord{" +
"id=" + id +
", CreateDate='" + CreateDate + '\'' +
", Count='" + Count + '\'' +
'}';
}
public List<Product> getProducts() {
return products;
}
}

View File

@ -2,41 +2,28 @@ package ip.labwork.student.model;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column()
private String ProductName;
private Integer Price;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "products_component",
joinColumns = @JoinColumn(name = "product_fk"),
inverseJoinColumns = @JoinColumn(name = "component_fk"))
private List<Component> components;
private String productName;
private Integer price;
@OneToMany(mappedBy = "product", cascade = CascadeType.ALL)
private Set<ProductComponents> components = new HashSet<>();
@ManyToMany(mappedBy = "products", fetch = FetchType.EAGER)
private List<Order> ords;
public void addComponent(Component component) {
if (components == null){
components = new ArrayList<>();
}
this.components.add(component);
if (component.getProduct() == null) {
component.setProduct(this);
}
}
public Product(){
}
public Product(String ProductName, Integer Price) {
this.ProductName = ProductName;
this.Price = Price;
}
public Product(String productName, Integer price, Set<ProductComponents> components) {
this.productName = productName;
this.price = price;
this.components = components;
}
public Long getId() {
@ -44,21 +31,41 @@ public class Product {
}
public String getProductName() {
return ProductName;
return productName;
}
public void setProductName(String ProductName) {
this.ProductName = ProductName;
public void setProductName(String productName) {
this.productName = productName;
}
public Integer getPrice() {
return Price;
return price;
}
public void setPrice(Integer Price) {
this.Price = Price;
public void setPrice(Integer price) {
this.price = price;
}
public Set<ProductComponents> getComponents() {
return components;
}
public void setComponents(Set<ProductComponents> components) {
this.components = components;
}
public void update(Product product){
this.productName = product.productName;
this.price = product.price;
this.components = product.getComponents();
}
public void addComponent(ProductComponents productComponents){
this.components.add(productComponents);
}
public void removeComponent(ProductComponents productComponents){
this.components.remove(productComponents);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
@ -76,30 +83,8 @@ public class Product {
public String toString() {
return "Product{" +
"id=" + id +
", ProductName='" + ProductName + '\'' +
", Price='" + Price + '\'' +
", productName='" + productName + '\'' +
", price='" + price + '\'' +
'}';
}
public List<Component> getComponents() {
return components;
}
public List<Order> getOrder() {
/*if(products.contains(product)){
return true;
}else{
return false;
}*/
return ords;
}
public void setOrder(Order order) {
if (ords == null){
ords = new ArrayList<>();
}
this.ords.add(order);
if (!order.getProducts().contains(this)) { // warning this may cause performance issues if you have a large data set since this operation is O(n)
order.getProducts().add(this);
}
}
}

View File

@ -0,0 +1,62 @@
package ip.labwork.student.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
@Entity
public class ProductComponents {
@EmbeddedId
private ProductComponentsKey id;
@ManyToOne
@MapsId("componentId")
@JoinColumn(name = "component_id")
private Component component;
@ManyToOne
@MapsId("productId")
@JoinColumn(name = "product_id")
@JsonIgnore
private Product product;
private Integer count;
public ProductComponents() {
}
public ProductComponents(Component component, Product product, Integer count) {
this.component = component;
this.id.setComponentId(component.getId());
this.id.setProductId(product.getId());
this.product = product;
this.count = count;
}
public ProductComponentsKey getId() {
return id;
}
public void setId(ProductComponentsKey id) {
this.id = id;
}
public Component getComponent() {
return component;
}
public void setComponent(Component component) {
this.component = component;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}

View File

@ -0,0 +1,47 @@
package ip.labwork.student.model;
import jakarta.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
@Embeddable
public class ProductComponentsKey implements Serializable {
private Long productId;
private Long componentId;
public ProductComponentsKey() {
}
public ProductComponentsKey(Long productId, Long componentId) {
this.productId = productId;
this.componentId = componentId;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public Long getComponentId() {
return componentId;
}
public void setComponentId(Long componentId) {
this.componentId = componentId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ProductComponentsKey that)) return false;
return Objects.equals(getProductId(), that.getProductId()) && Objects.equals(getComponentId(), that.getComponentId());
}
@Override
public int hashCode() {
return Objects.hash(getProductId(), getComponentId());
}
}

View File

@ -36,18 +36,18 @@ public class ComponentService {
@Transactional(readOnly = true)
public List<Component> findAllComponent() {
return em.createQuery("select s from Component s", Component.class)
return em.createQuery("select c from Component c", Component.class)
.getResultList();
}
@Transactional
public Component updateComponent(Long id, String ComponentName, Integer Count) {
if (!StringUtils.hasText(ComponentName) || Count != 0) {
if (!StringUtils.hasText(ComponentName) || Count == 0) {
throw new IllegalArgumentException("Component is null or empty");
}
final Component currentComponent = findComponent(id);
currentComponent.setComponentName(ComponentName);
currentComponent.setCount(Count);
currentComponent.setPrice(Count);
return em.merge(currentComponent);
}
@ -57,7 +57,10 @@ public class ComponentService {
em.remove(currentComponent);
return currentComponent;
}
@Transactional
public void check(){
int s = 5;
}
@Transactional
public void deleteAllComponent() {
em.createQuery("delete from Component").executeUpdate();

View File

@ -1,70 +0,0 @@
package ip.labwork.student.service;
import ip.labwork.student.model.Order;
import ip.labwork.student.model.Product;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class OrdService {
@PersistenceContext
private EntityManager em;
@Transactional
public Order addOrd(Date CreateDate, Integer Price, ArrayList<Product> products) {
if (!StringUtils.hasText(CreateDate.toString())) {
throw new IllegalArgumentException("Ord is null or empty");
}
final Order order = new Order(new Date(), Price);
for (int i = 0 ; i < products.size(); i++){
order.addProduct(products.get(i));
}
em.persist(order);
return order;
}
@Transactional(readOnly = true)
public Order findOrd(Long id) {
final Order product = em.find(Order.class, id);
if (product == null) {
throw new EntityNotFoundException(String.format("Ord with id [%s] is not found", id));
}
return product;
}
@Transactional(readOnly = true)
public List<Order> findAllOrd() {
return em.createQuery("select s from Order s", Order.class)
.getResultList();
}
@Transactional
public Order updateOrd(Long id, Date CreateDate, Integer Count) {
if (!StringUtils.hasText(CreateDate.toString())) {
throw new IllegalArgumentException("Ord is null or empty");
}
final Order currentOrd = findOrd(id);
currentOrd.setCreateDate(CreateDate);
currentOrd.setCount(Count);
return em.merge(currentOrd);
}
@Transactional
public Order deleteOrd(Long id) {
final Order currentOrd = findOrd(id);
em.remove(currentOrd);
return currentOrd;
}
@Transactional
public void deleteAllOrd() {
em.createQuery("delete from Order").executeUpdate();
}
}

View File

@ -2,14 +2,18 @@ package ip.labwork.student.service;
import ip.labwork.student.model.Component;
import ip.labwork.student.model.Product;
import ip.labwork.student.model.ProductComponents;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class ProductService {
@ -17,18 +21,26 @@ public class ProductService {
private EntityManager em;
@Transactional
public Product addProduct(String ProductName, Integer Price, List<Component> components) {
if (!StringUtils.hasText(ProductName)) {
throw new IllegalArgumentException("Product is null or empty");
public Product addProduct(String productName, Integer price, Set<ProductComponents> components){
Product product = new Product(productName,price,components);
Product newProduct = new Product();
newProduct.setProductName(product.getProductName());
newProduct.setPrice(product.getPrice());
newProduct.getComponents().addAll((product.getComponents()
.stream()
.map(productComponents -> {
Component component = em.find(Component.class, productComponents.getComponent().getId());
ProductComponents newProductComponents = new ProductComponents();
newProductComponents.setComponent(component);
newProductComponents.setProduct(newProduct);
newProductComponents.setCount(productComponents.getCount());
return newProductComponents;
})
.collect(Collectors.toSet())
));
em.persist(newProduct);
return newProduct;
}
final Product product = new Product(ProductName, Price);
for (int i = 0; i < components.size(); i++){
product.addComponent(components.get(i));
}
em.persist(product);
return product;
}
@Transactional(readOnly = true)
public Product findProduct(Long id) {
final Product product = em.find(Product.class, id);
@ -61,7 +73,10 @@ public class ProductService {
em.remove(currentProduct);
return currentProduct;
}
@Transactional
public void check(){
int s = 5;
}
@Transactional
public void deleteAllProduct() {
em.createQuery("delete from Product").executeUpdate();

View File

@ -1,12 +1,10 @@
package ip.labwork;
import ip.labwork.student.model.Component;
import ip.labwork.student.model.Order;
import ip.labwork.student.model.Product;
import ip.labwork.student.model.ProductComponents;
import ip.labwork.student.service.ComponentService;
import ip.labwork.student.service.OrdService;
import ip.labwork.student.service.ProductService;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
@ -14,195 +12,34 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
@SpringBootTest
public class JpaStudentTests {
private static final Logger log = LoggerFactory.getLogger(JpaStudentTests.class);
@Autowired
private ComponentService componentService;
ComponentService componentService;
@Autowired
private ProductService productService;
@Autowired
private OrdService ordService;
ProductService productService;
@Test
void testComponentCreate() {
componentService.deleteAllComponent();
final Component component = componentService.addComponent("Помидор", 3);
log.info(component.toString());
Assertions.assertNotNull(component.getId());
}
@Test
void testComponentRead() {
componentService.deleteAllComponent();
final Component component = componentService.addComponent("Помидор", 3);
log.info(component.toString());
final Component findComponent = componentService.findComponent(component.getId());
log.info(findComponent.toString());
Assertions.assertEquals(component, findComponent);
}
@Test
void testComponentReadNotFound() {
componentService.deleteAllComponent();
Assertions.assertThrows(EntityNotFoundException.class, () -> componentService.findComponent(-1L));
}
@Test
void testComponentReadAll() {
componentService.deleteAllComponent();
componentService.addComponent("Помидор", 3);
componentService.addComponent("Огруец", 2);
final List<Component> components = componentService.findAllComponent();
log.info(components.toString());
Assertions.assertEquals(components.size(), 2);
}
@Test
void testComponentReadAllEmpty() {
componentService.deleteAllComponent();
final List<Component> components = componentService.findAllComponent();
log.info(components.toString());
Assertions.assertEquals(components.size(), 0);
}
@Test
void testProductCreate() {
productService.deleteAllProduct();
componentService.deleteAllComponent();
final Component component1 = componentService.addComponent("Помидор", 3);
final Component component2 = componentService.addComponent("Булочка", 2);
final Component component3 = componentService.addComponent("Огурец", 3);
ArrayList<Component> components = new ArrayList<>();
components.add(component1);
components.add(component2);
components.add(component3);
final Product product = productService.addProduct("Бургер", 300, components);
log.info(product.toString());
final Product product1 = productService.findProduct(product.getId());
Assertions.assertTrue(product1.getComponents().contains(component1));
Assertions.assertEquals(product,product1);
productService.deleteAllProduct();
Assertions.assertEquals(productService.findAllProduct().size(), 0);
Assertions.assertThrows(EntityNotFoundException.class, () -> productService.findProduct(-1L));
}
/* @Test
void testProductRead() {
productService.deleteAllProduct();
final Product product = productService.addProduct("Бургер", 300);
log.info(product.toString());
final Product findProduct = productService.findProduct(product.getId());
log.info(findProduct.toString());
Assertions.assertEquals(product, findProduct);
}
*/
@Test
void testProductReadNotFound() {
productService.deleteAllProduct();
Assertions.assertThrows(EntityNotFoundException.class, () -> productService.findProduct(-1L));
}
@Test
void testProductReadAll() {
productService.deleteAllProduct();
//productService.addProduct("Бургер", 300);
//productService.addProduct("Хот-дог", 200);
final List<Product> products = productService.findAllProduct();
log.info(products.toString());
Assertions.assertEquals(products.size(), 0);
}
@Test
void testProductReadAllEmpty() {
productService.deleteAllProduct();
final List<Product> products = productService.findAllProduct();
log.info(products.toString());
Assertions.assertEquals(products.size(), 0);
}
@Test
void testOrderCreate() {
productService.deleteAllProduct();
componentService.deleteAllComponent();
ordService.deleteAllOrd();
final Component component1 = componentService.addComponent("Помидор", 3);
final Component component2 = componentService.addComponent("Булочка", 2);
final Component component3 = componentService.addComponent("Огурец", 3);
ArrayList<Component> components = new ArrayList<>();
components.add(component1);
components.add(component2);
components.add(component3);
final Product product = productService.addProduct("Бургер", 300, components);
ArrayList<Product> products = new ArrayList<>();
products.add(product);
final Order ord = ordService.addOrd(new Date(), 3, products);
ordService.addOrd(new Date(), 4,products);
ordService.addOrd(new Date(), 5,products);
ordService.addOrd(new Date(), 6,products);
log.info(ord.toString());
Assertions.assertEquals(3, ordService.findOrd(ord.getId()).getProducts().get(0).getComponents().size());
Assertions.assertEquals(1, ordService.findOrd(ord.getId()).getProducts().size());
Assertions.assertEquals(4, ordService.findAllOrd().size());
final Order ord1 = ordService.findOrd(ord.getId());
Assertions.assertEquals(ord1, ord);
ordService.deleteAllOrd();
Assertions.assertThrows(EntityNotFoundException.class, () -> ordService.findOrd(-1L));
Assertions.assertEquals(0, ordService.findAllOrd().size());
}
/*@Test
void testOrderRead() {
ordService.deleteAllOrd();
final Ord Order = ordService.addOrd(new Date(), 3);
log.info(Order.toString());
final Ord findOrder = ordService.findOrd(Order.getId());
log.info(findOrder.toString());
Assertions.assertEquals(Order, findOrder);
}*/
/* @Test
void testOrderReadNotFound() {
ordService.deleteAllOrd();
Assertions.assertThrows(EntityNotFoundException.class, () -> ordService.findOrd(-1L));
}
@Test
void testOrderReadAll() {
ordService.deleteAllOrd();
ordService.addOrd(new Date(), 3);
ordService.addOrd(new Date(), 2);
final List<Ord> Orders = ordService.findAllOrd();
log.info(Orders.toString());
Assertions.assertEquals(Orders.size(), 2);
}*/
@Test
void testOrderReadAllEmpty() {
productService.deleteAllProduct();
componentService.deleteAllComponent();
ordService.deleteAllOrd();
final Component component1 = componentService.addComponent("Помидор", 3);
final Component component2 = componentService.addComponent("Булочка", 2);
final Component component3 = componentService.addComponent("Огурец", 3);
ArrayList<Component> components = new ArrayList<>();
components.add(component1);
components.add(component2);
components.add(component3);
final Product product = productService.addProduct("Бургер", 300, components);
ArrayList<Product> products = new ArrayList<>();
products.add(product);
final Order ord = ordService.addOrd(new Date(), 3, products);
Assertions.assertEquals(ordService.findAllOrd().size(), 1);
ordService.deleteOrd(ord.getId());
Assertions.assertEquals(ordService.findAllOrd().size(), 0);
void test(){
Component component = componentService.addComponent("Помидор", 10);
Component component1 = componentService.addComponent("Огурец", 20);
Set<ProductComponents> temp = new HashSet<>();
ProductComponents tem = new ProductComponents();
tem.setComponent(component);
tem.setCount(5);
ProductComponents te = new ProductComponents();
te.setComponent(component1);
te.setCount(6);
temp.add(tem);
temp.add(te);
Product product = new Product("Гамбургер", 100, temp);
productService.check();
componentService.check();
productService.addProduct("Гамбургер", 100, temp);
productService.check();
componentService.check();
}
}