OiO.lk Blog java Why are the product.id and recipeIngredient.product fields null in the logs?
java

Why are the product.id and recipeIngredient.product fields null in the logs?


And what might be causing the total unit cost of the ingredients to always calculate to zero?

Important: Despite these issues in the logs, the product and the unit cost of the ingredients are saved in the database without any problems.

Entity ProductDTO:

public class ProductDTO {

    private Long id;
    private String name;
    private String description;
    private BigDecimal price;
    private CategoryDTO category;
    private SupplierDTO supplier;
    private int quantityInStock;
    private Date expirationDate;
    private Date registrationDate;
    private String unitOfMeasure;
    private boolean isIngredient;
    private List<RecipeIngredientDTO> recipeIngredients = new ArrayList<>();

    // getters and setters

}

Entity RecipeIngredientDTO:

public class RecipeIngredientDTO {

    private Long id;
    private String ingredientName;
    private BigDecimal quantity;
    private BigDecimal unitCost;
    private String unit;
    private BigDecimal totalCost;

    // getters and setters

}

Class ProductDomainService:

@Service
public class ProductDomainService {

   public void validateRecipeIngredients(List<RecipeIngredient> recipeIngredients) {
        if (recipeIngredients == null || recipeIngredients.isEmpty()) {
            throw new InvalidProductException("Message here.");
        }

        for (RecipeIngredient ingredient : recipeIngredients) {
            if (ingredient.getQuantity() == null || ingredient.getQuantity().compareTo(BigDecimal.ZERO) <= 0) {
                throw new InvalidProductException("Message here.");
            }
            if (ingredient.getIngredientName() == null || ingredient.getIngredientName().trim().isEmpty()) {
                throw new InvalidProductException("Message here.");
            }
            if (ingredient.getTotalCost() == null || ingredient.getTotalCost().compareTo(BigDecimal.ZERO) <= 0) {
                throw new InvalidProductException("Message here.");
            }
        }
    }

    public BigDecimal calculateProductProductionCost(List<RecipeIngredient> ingredients) {
        return ingredients.stream()
                .map(RecipeIngredient::getTotalCost)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

}

Class ProductService:

@Service
public class ProductService {
    @Transactional
    public Product createProduct(ProductDTO productDTO) {
        if (productDTO.getRecipeIngredients() == null || productDTO.getRecipeIngredients().isEmpty()) {
            throw new InvalidProductException("Message here.");
        }

        Category category = categoryDomainService.findOrCreateCategory(productDTO.getCategory());

        Product product = mapToProduct(productDTO);
        product.setCategory(category);

        Product savedProduct = productRepository.save(product);

        List<RecipeIngredient> recipeIngredients = productDTO.getRecipeIngredients().stream()
                .map(this::mapToRecipeIngredient)
                .collect(Collectors.toList());
        productDomainService.validateRecipeIngredients(recipeIngredients);
        System.out.println("Message here: " + recipeIngredients);

        final Product finalSavedProduct = savedProduct;
        recipeIngredients.forEach(ingredient -> ingredient.setProduct(finalSavedProduct));
        System.out.println("Produto salvo: " + finalSavedProduct);

        saveRecipeIngredients(finalSavedProduct, productDTO.getRecipeIngredients());

        savedProduct = productRepository.findById(finalSavedProduct.getId())
                .orElseThrow(() -> new EntityNotFoundException("Product not found."));
        Hibernate.initialize(finalSavedProduct.getRecipeIngredients());

        savedProduct.getRecipeIngredients().forEach(ingredient ->
                System.out.println("Ingrediente: " + ingredient.getIngredientName() +
                        ", Quantity: " + ingredient.getQuantity() +
                        ", Unit cost: " + ingredient.getUnitCost() +
                        ", Unit: " + ingredient.getUnit() +
                        ", Total cost: " + ingredient.getTotalCost()));

        BigDecimal totalCost = productDomainService.calculateProductProductionCost(savedProduct.getRecipeIngredients());
        System.out.println("Total cost: " + totalCost);

        savedProduct.setPrice(totalCost);
        productRepository.save(savedProduct);

        productPriceHistoryDomainService.registerPriceChange(
                savedProduct,
                savedProduct.getPrice(),
                "Final price");

        return savedProduct;
    }

    public void saveRecipeIngredients(Product product, List<RecipeIngredientDTO> ingredients) {
        if (ingredients != null && !ingredients.isEmpty()) {
            for (RecipeIngredientDTO ingredientDTO : ingredients) {
                RecipeIngredient ingredient = new RecipeIngredient();

                ingredient.setProduct(product);

                if (ingredientDTO.getQuantity() == null || ingredientDTO.getUnitCost() == null) {
                    throw new InvalidProductException("Message here.");
                }

                ingredient.setIngredientName(ingredientDTO.getIngredientName());
                ingredient.setQuantity(ingredientDTO.getQuantity());
                ingredient.setUnitCost(ingredientDTO.getUnitCost());
                ingredient.setUnit(ingredientDTO.getUnitOfMeasure());
                              ingredient.setTotalCost(ingredientDTO.getQuantity().multiply(ingredientDTO.getUnitCost()));

                ingredient.setProduct(product);
                recipeIngredientRepository.save(ingredient);
            }
        }
    }
}

Logs:

Ingredients: [RecipeIngredient{id=null, ingredientName="Cake ingredient", quantity=1.5, unitCost=1.25, unit="unidade", totalCost=1.875, product=null}]

Total cost: 0

The problem:

The products are being created and saved correctly in the database, which is important. However, the problem I am trying to solve, as indicated by the log messages, is that the ingredient ID is null, the product is null, and the total cost of the ingredient unit is zero.

The data sent from the frontend is being saved exactly as it should be. I suspect that the issue may be related to synchronization.



You need to sign in to view this answers

Exit mobile version