habuma / spring-in-action-5-samples

Home for example code from Spring in Action 5.
Apache License 2.0
1.21k stars 1.04k forks source link

Chapter 3: JPA H2 - taco_ingredients and taco_order_tacos empty #95

Open OliverZott opened 4 years ago

OliverZott commented 4 years ago

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?

JiashengHong commented 3 years ago

I have the same problem. Did you solve it?

OliverZott commented 3 years ago

No sorry, I couldnt solve it yet.

DMDoom commented 3 years ago

same issue

cnwachukwu5 commented 3 years ago

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

DMDoom commented 3 years ago

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.

chenqping commented 3 years ago

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