Важно! Несмотря на эти проблемы в журналах, продукт и стоимость единицы ингредиентов без проблем сохраняется в базе данных.
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
}
Код: Выделить всё
public class RecipeIngredientDTO {
private Long id;
private String ingredientName;
private BigDecimal quantity;
private BigDecimal unitCost;
private String unit;
private BigDecimal totalCost;
// getters and setters
}
Код: Выделить всё
@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, а общая стоимость единицы ингредиента равна нулю.
Данные, отправленные из внешнего интерфейса, сохраняются именно так, как и должно быть. Подозреваю, что проблема может быть связана с синхронизацией.
А вот лог совершенно нового продукта, который я недавно зарегистрировал:
Спящий режим: вставить в категорию (имя) значения (?)
Received ProductDTO:
com.example.bms_backend.application. Product.dto.ProductDTO@3a621136
Спящий режим: выберите c1_0.id,c1_0.name из категории c1_0, где Upper(c1_0.name)=upper(?)
Спящий режим: выберите c1_0.id,c1_0.name из категории c1_0, где верхний(c1_0.name)=upper(?)
Спящий режим: вставить в поставщика (адрес, город, contact_info,country,email,name,phone,postal_code,registration_date,state) значения (?,?,?,?,?,?,?,?,?,?)
Гибернация : вставить в продукт (category_id,description,expiration_date,is_ingredient,name,price,quantity_in_stock,registration_date,supplier_id,unit_of_measure) значения (?,?,?,?,?,?,?,?,?,?)
Подробнее здесь: https://stackoverflow.com/questions/790 ... n-the-logs