spring-in-action-5-samples icon indicating copy to clipboard operation
spring-in-action-5-samples copied to clipboard

Chapter 3: JPA H2 - taco_ingredients and taco_order_tacos empty

Open OliverZott opened this issue 5 years ago • 6 comments

Both with JPA implementation (chapter 3.2) and with the Jdbc Template implementation (chapter 3.1.2) the TACO_INGREDIENTS and the TACO_ORDER_TACOS tables re empty.

It seems as if its not the same order-instances (see pictures). But the @SessionAttributes("order") is annotated correctly in the DesignController and the OrderController.

Screenshot from 2020-09-18 10-42-51 Screenshot from 2020-09-18 10-44-05

Is there any way to fix this?

OliverZott avatar Sep 18 '20 08:09 OliverZott

I have the same problem. Did you solve it?

JiashengHong avatar Dec 26 '20 13:12 JiashengHong

No sorry, I couldnt solve it yet.

OliverZott avatar Dec 28 '20 14:12 OliverZott

same issue

DMDoom avatar Mar 05 '21 15:03 DMDoom

The problem is because of this statement model.addAttribute("order", new Order()); in public String orderForm(Model model) in the OrderController. This is because that line is creating and adding a new Order attribute to the model which overrides the Order object created and added to the model attribute in the DesignTacoController. Hence, it does not have any association with the created Tacos already saved to the DB.

Wrapping a condition around that statement as below will resolve the issue:

if (!model.containsAttribute("order")) { model.addAttribute("order", new Order()); }

This ensures that no new Order object is created if there is already an existing Order object attribute in the Model object

cnwachukwu5 avatar Mar 06 '21 17:03 cnwachukwu5

The problem is because of this statement model.addAttribute("order", new Order()); in public String orderForm(Model model) in the OrderController. This is because that line is creating and adding a new Order attribute to the model which overrides the Order object created and added to the model attribute in the DesignTacoController. Hence, it does not have any association with the created Tacos already saved to the DB.

Wrapping a condition around that statement as below will resolve the issue:

if (!model.containsAttribute("order")) { model.addAttribute("order", new Order()); }

This ensures that no new Order object is created if there is already an existing Order object attribute in the Model object

Thank you, it worked!

As for the TACO_INGREDIENTS being empty, make sure to implement IngredientByIdConverter from ch03/tacos-jdbc/src/main/java/tacos/web/IngredientByIdConverter.java. This fixed the issue for me and now everything works properly.

DMDoom avatar Mar 07 '21 22:03 DMDoom

I use spring-boot 2.5.0 and don't meet this issue, the code just works fine. can you show your designController?

chenqping avatar Jun 11 '21 03:06 chenqping