Почему поля 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, а общая стоимость единицы ингредиента равна нулю.
Данные, отправленные из внешнего интерфейса, сохраняются именно так, как и должно быть. Подозреваю, что проблема может быть связана с синхронизацией.
А вот лог совершенно нового продукта, который я недавно зарегистрировал:
Hibernate: insert into category (name) values (?)

Received ProductDTO:

com.example.bms_backend.application.product.dto.ProductDTO@3a621136

Hibernate: select c1_0.id,c1_0.name from category c1_0 where upper(c1_0.name)=upper(?)

Hibernate: select c1_0.id,c1_0.name from category c1_0 where upper(c1_0.name)=upper(?)

Hibernate: insert into supplier (address,city,contact_info,country,email,name,phone,postal_code,registration_date,state) values (?,?,?,?,?,?,?,?,?,?)

Hibernate: insert into product (category_id,description,expiration_date,is_ingredient,name,price,quantity_in_stock,registration_date,supplier_id,unit_of_measure) values (?,?,?,?,?,?,?,?,?,?)

Ingredients: [RecipeIngredient{id=null, ingredientName='Flour', quantity=1.5, unitCost=2.6, unit='unidade', totalCost=3.90, product=null}]

Saved product: com.example.bms_backend.domain.product.models.Product@30

Hibernate: insert into recipe_ingredient (ingredient_name,product_id,quantity,total_cost,unit,unit_cost) values (?,?,?,?,?,?)

Total cost: 0

Hibernate: insert into product_price_history (current_price,modification_date,modification_reason,previous_price,product_id) values (?,?,?,?,?)

Hibernate: update product set category_id=?,description=?,expiration_date=?,is_ingredient=?,name=?,price=?,quantity_in_stock=?,registration_date=?,supplier_id=?,unit_of_measure=? where id=?

Hibernate: select p1_0.category_id,p1_0.id,p1_0.description,p1_0.expiration_date,p1_0.is_ingredient,p1_0.name,p1_0.price,p1_0.quantity_in_stock,p1_0.registration_date,p1_0.supplier_id,p1_0.unit_of_measure from product p1_0 where p1_0.category_id=?

2024-10-16T18:39:51.868-03:00 WARN 28517 --- [bakery-management-system] [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Ignoring exception, response committed already: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Document nesting depth (1001) exceeds the maximum allowed (1000, from `StreamWriteConstraints.getMaxNestingDepth()`)

2024-10-16T18:39:51.868-03:00 WARN 28517 --- [bakery-management-system] [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Document nesting depth (1001) exceeds the maximum allowed (1000, from `StreamWriteConstraints.getMaxNestingDepth()`)]


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

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