Значение типа числа, отправленное через angular, становится равным нулю в Spring REST API - PullRequest
0 голосов
/ 17 марта 2020

Я отправляю значение типа номер в запросе на публикацию из angular в Spring REST API, который затем сохраняется в базе данных с помощью Hibernate. Проблема в том, что значение получено 0 в API. Это форма группы в моем компоненте, откуда я отправляю запрос:

 formData = new FormData();
productFormGroup = new FormGroup({
name: new FormControl("", Validators.required),
category: new FormControl("", Validators.required),
model: new FormControl("", Validators.required),
barcode: new FormControl("", Validators.required),
unit: new FormControl("", Validators.required),
cost: new FormControl("", Validators.required),
minStock: new FormControl("", Validators.required),
description: new FormControl("", Validators.required),
manufacturer: new FormControl("", Validators.nullValidator),
brand: new FormControl("", Validators.nullValidator),
length: new FormControl("", Validators.nullValidator),
width: new FormControl("", Validators.nullValidator),
height: new FormControl("", Validators.nullValidator),
weight: new FormControl("", Validators.nullValidator),
openingStockUnitCost: new FormControl("",Validators.nullValidator),   
openingStock: new FormControl("",Validators.nullValidator),
openingStockWarehouse: new FormControl("",Validators.nullValidator),
foreignName: new FormControl("", Validators.nullValidator),
foreignSKU: new FormControl("", Validators.nullValidator),
preferred_supplier: new FormControl("", Validators.nullValidator) 
});

Это моя функция onSubmit:

onSubmit() {
    this.productSubmit = true;
    if (this.productFormGroup.valid && !this.isTableEmpty && this.isFormValid) {
      this.isLoading = true;
      this.product.name = this.f.name.value;
      this.product.productCategory = this.f.category.value;
      this.product.model = this.f.model.value;
      this.product.barcode = this.f.barcode.value;
      this.product.unit = this.f.unit.value;
      this.product.cost = this.f.cost.value;
      this.product.minimumStockLevel = this.f.minStock.value;
      this.product.description = this.f.description.value;
      this.product.length=this.f.length.value;
      this.product.width=this.f.width.value;
      this.product.height=this.f.height.value;
      this.product.weight=this.f.weight.value;

      this.f.openingStockUnitCost.setValue(this.f.cost.value);
      this.product.openingStockUnitCost=this.f.openingStockUnitCost.value;
      this.product.openingStock=this.f.openingStock.value;
      if (this.f.openingStockWarehouse.value) {
        this.product.openingStockWarehouse=this.f.openingStockWarehouse.value;
      } 
      else {

        for (let index = 0; index < this.warehousesDropDown.length; index++) {
          if(this.warehousesDropDown[index].isDefault){
            this.product.openingStockWarehouse=this.warehousesDropDown[index];
            break;
          }  
        }
      }
      if (this.f.manufacturer.value) {
        this.product.manufacturer = this.f.manufacturer.value;
      } else {
        this.product.manufacturer = null;
      }
      if (this.f.brand.value) {
        this.product.brand = this.f.brand.value;
      } else {
        this.product.brand = null;
      }
      if (this.f.foreignName.value) {
        this.product.foreign_name=this.f.foreignName.value;
      } else {
        let foreignName=this.f.name.value;
        this.product.foreign_name=foreignName;
      }
      if (this.f.foreignSKU.value) {
        this.product.foreign_sku=this.f.foreignSKU.value;
      } else {
        let foreignSKU=this.f.model.value;
        this.product.foreign_sku=foreignSKU;
      }
      if (this.f.preferred_supplier.value) {
        this.product.preferred_supplier=this.f.preferred_supplier.value;
      } else {
        this.product.preferred_supplier=null;
      }

      this.product.prices = this.myPriceLists;
      this.formData.append('product', new Blob([JSON.stringify(this.product, this.appService.jsonStringifier)],{ type: "application/json" }));

      for (let image of this.images) {
        this.formData.append('images', image, image.name);
      }
      console.log(this.product.openingStockUnitCost);
      this.productService.saveProduct(this.formData).subscribe(
        () => {
          this.messageService.add({
            severity: "info",
            summary: "Success",
            detail: "Product Successfully Added"
          });
          this.router.navigate(["/loggedIn", "product", "list"]);
        },
        error => {
          this.productErrors = this.appService.errorObjToMap(
            error.error.errors
          );
          this.productSuccess = error.success;
          this.isLoading = false;

          if (this.productErrors.size == 0) {
            this.messageService.add({
              severity: "error",
              summary: "Failure",
              detail: "Product not added."
            });
          }
        },
        () => {
          this.successAlert = true;
          this.isLoading = false;
        }
      );
    }

  }

По сути, я пытаюсь назначить значение стоимости для открытиеStockUnitCost без каких-либо входных данных. Все работает нормально, за исключением, что opensStockUnitCost становится равным нулю на внутреннем API.

Это мой метод контроллера Spring, который обрабатывает запрос:

private ResponseEntity saveProduct(Integer id, @Valid @RequestBody Product product, MultipartFile[] images, BindingResult bindingResult, HttpServletRequest request) throws IOException {
        HashMap response = new HashMap();
        boolean success = false;
        List errors = new ArrayList();
        HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
        String message = "";
        Map data = new HashMap();
        Slugify slg = new Slugify();
        String directory = "/var/www/images";

        Set<ProductImage> productImages = new HashSet<>();

Когда Выполнение System.out.println для product.getOpeningStockUnitCost (); он дает «0,00»

Это класс модели

package com.bmis.app.model;

import com.bmis.app.model.serializer.ProductCategorySerializer;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;

import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.DecimalMin;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "products")
@JsonIdentityInfo(generator = ObjectIdGenerators.None.class, property = "id", scope = Product.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Product implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    public Integer getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }


    @Column(name = "name", nullable = false)
    @NotBlank(message = "Name is required")
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    @Column(name = "barcode", nullable = false)
    @NotEmpty(message = "Barcode is required")
    private String barcode;

    public void setBarcode(String barcode) {
        this.barcode = barcode;
    }

    public String getBarcode() {
        return this.barcode;
    }

    @Column(name = "model")
    private String model;

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    @Column(name = "description")
    private String description;

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDescription() {
        return this.description;
    }

    @Column(name = "image_file_name")
    private String imageFileName;

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public String getImageFileName() {
        return this.imageFileName;
    }


    @Column(name = "minimum_stock_level", nullable = false)
    private int minimumStockLevel;

    public void setMinimumStockLevel(int minimumStockLevel) {
        this.minimumStockLevel = minimumStockLevel;
    }

    public int getMinimumStockLevel() {
        return this.minimumStockLevel;
    }


    @Column(name = "cost", nullable = false)
    @DecimalMin(message = "Cost should be greater than 1", value = "1")
    private float cost;

    public void setCost(float cost) {
        this.cost = cost;
    }

    public float getCost() {
        return this.cost;
    }

    @Column(name = "status")
    private boolean status;

    public void setStatus(boolean status) {
        this.status = status;
    }

    public boolean getStatus() {
        return this.status;
    }

    @Column(name = "length")
    private float length;

    public float getLength() {
        return length;
    }

    public void setLength(float length) {
        this.length = length;
    }

    @Column(name = "width")
    private float width;

    public float getWidth() {
        return width;
    }

    public void setWidth(float width) {
        this.width = width;
    }
    @Column(name = "height")
    private float height;

    public float getHeight() {
        return height;
    }

    public void setHeight(float height) {
        this.height = height;
    }

    @Column(name = "weight")
    private float weight;

    public float getWeight() {
        return weight;
    }

    public void setWeight(float weight) {
        this.weight = weight;
    }


    @Column(name = "foreign_name")
    private String foreign_name;

    public String getForeign_name() {
        return foreign_name;
    }

    public void setForeign_name(String foreign_name) {
        this.foreign_name = foreign_name;
    }


    @Column(name = "foreign_sku")
    private String foreign_sku;

    public String getForeign_sku() {
        return foreign_sku;
    }

    public void setForeign_sku(String foreign_sku) {
        this.foreign_sku = foreign_sku;
    }
    @Column(name = "opening_stock_unit_cost", nullable = false)
    @DecimalMin(message = "Opening Stock Unit Cost should be greater than 1", value = "1")
    private float opening_stock_unit_cost;

    public float getOpening_stock_unit_cost() {
        return opening_stock_unit_cost;
    }

    public void setOpening_stock_unit_cost(float opening_stock_unit_cost) {
        this.opening_stock_unit_cost = opening_stock_unit_cost;
    }

    @ManyToOne
    @JoinColumn(name = "category_id", referencedColumnName = "id")
    @JsonSerialize(using = ProductCategorySerializer.class)
    private ProductCategory productCategory;

    public void setProductCategory(ProductCategory productCategory) {
        this.productCategory = productCategory;
    }

    public ProductCategory getProductCategory() {
        return this.productCategory;
    }

    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JsonManagedReference(value = "PI")
    private Set<ProductImage> productImages = new HashSet<ProductImage>();

    public Set<ProductImage> getProductImages() {
        return productImages;
    }

    public void setProductImages(Set<ProductImage> productImages) {
        this.productImages = productImages;
    }

    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    private Set<CustomAttribute> customAttributes = new HashSet<CustomAttribute>();

    public Set<CustomAttribute> getCustomAttributes() {
        return customAttributes;
    }

    public void setCustomAttributes(Set<CustomAttribute> customAttributes) {
        this.customAttributes.addAll(customAttributes);
    }

    @ManyToOne
    @JoinColumn(name = "unit_id", referencedColumnName = "id")
    private Unit unit;

    public void setUnit(Unit unit) {
        this.unit = unit;
    }

    public Unit getUnit() {
        return this.unit;
    }


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "manufacturer_id", referencedColumnName = "id")
    private Manufacturer manufacturer;


    public Manufacturer getManufacturer() {
        return this.manufacturer;
    }

    public void setManufacturer(Manufacturer manufacturer) {
        this.manufacturer = manufacturer;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "brand_id", referencedColumnName = "id")
    private Brand brand;
    public Brand getBrand() {
        return this.brand;
    }


    public void setBrand(Brand brand) {
        this.brand = brand;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "preferred_supplier_id", referencedColumnName = "id")
    private User preferred_supplier;

    public User getPreferred_supplier() {
        return preferred_supplier;
    }

    public void setPreferred_supplier(User preferred_supplier) {
        this.preferred_supplier = preferred_supplier;
    }

    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
    private Set<Price> prices = new HashSet<Price>();

    public void setPrices(Set<Price> prices) {
        this.prices.addAll(prices);
    }

    public Set<Price> getPrices() {
        return this.prices;
    }

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "product_locations", joinColumns = {
            @JoinColumn(name = "PRODUCT_ID", nullable = false, updatable = true)},
            inverseJoinColumns = {@JoinColumn(name = "LOCATION_ID",
                    nullable = false, updatable = false)})
    private Set<Location> locations = new HashSet<Location>(0);

    public Set<Location> getLocations() {
        return this.locations;
    }

    public void setLocations(Set<Location> locations) {
        this.locations = locations;
    }

    @Override
    public boolean equals(Object object) {
        if (object instanceof Product) {
            Product product = (Product) object;
            return
                    product.getId() == this.getId();
        }
        return true;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(id)
                .toHashCode();
    }

    @Transient
    private int openingStock;

    public int getOpeningStock() {
        return openingStock;
    }

    public void setOpeningStock(int openingStock) {
        this.openingStock = openingStock;
    }

    @Transient
    private Warehouse openingStockWarehouse;

    public Warehouse getOpeningStockWarehouse() {
        return openingStockWarehouse;
    }

    public void setOpeningStockWarehouse(Warehouse openingStockWarehouse) {
        this.openingStockWarehouse = openingStockWarehouse;
    }
}

Значение стоимости не становится равным нулю, это то, что меня тикает. Я пробовал много вещей, и я новичок в этом, поэтому я прошу прощения за код Месси. Буду очень признателен, если кто-нибудь сможет решить это за меня.

...