Почему поля Product.id и рецептИнгредиент.продукт в журналах имеют нулевые значения?JAVA

Программисты JAVA общаются здесь
Anonymous
Почему поля Product.id и рецептИнгредиент.продукт в журналах имеют нулевые значения?

Сообщение Anonymous »

И что может быть причиной того, что общая стоимость единицы ингредиентов всегда равна нулю?
Важно! Несмотря на эти проблемы в журналах, продукт и стоимость единицы ингредиентов без проблем сохраняется в базе данных.
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 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

}
Класс ProductDomainService:

Код: Выделить всё

@Service
public class ProductDomainService {

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

for (RecipeIngredient ingredient : recipeIngredients) {
if (ingredient.getQuantity() == null || ingredient.getQuantity().compareTo(BigDecimal.ZERO)  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 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);
}
}
}
}
Журналы:

Код: Выделить всё

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

Total cost: 0
Проблема:
Товары корректно создаются и сохраняются в базе данных, что немаловажно. Однако проблема, которую я пытаюсь решить, как видно из сообщений журнала, заключается в том, что идентификатор ингредиента имеет значение null, продукт имеет значение null, а общая стоимость единицы ингредиента равна нулю.
Данные, отправленные из внешнего интерфейса, сохраняются именно так, как и должно быть. Я подозреваю, что проблема может быть связана с синхронизацией.

Подробнее здесь: https://stackoverflow.com/questions/790 ... n-the-logs

Вернуться в «JAVA»