简体   繁体   中英

Problem with mapping and managing entity, Hibernate

I have two entities: Dish and Ingredient. I would like to add ingredients to dishes. When I was doing it with @ManyToMany relationship it works (I added, deleted, get all Dishes with table of ingredients - my endpoints works), but now I want to add extra column in cross-table DishIngredient .

So what I did was:

  • remove @ManyToMany , added @OneToMany / @ManyToOne
  • added cross-table as entity (java class) and added extra field (as my extra column in db)

Now, when I want for example GET all dishes or single dish by id I get error:

2020-06-25 17:01:25.995 ERROR 8528 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : BŁĄD: column ingredient1_.id does not exist
  Pozycja: 406
2020-06-25 17:01:26.000  WARN 8528 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not extract ResultSet; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not extract ResultSet (through reference chain: java.util.ArrayList[0]->.springbootdemo.dish.domain.Dish["dishIngredient"])]

My code is here, on branch: https://github.com/rhquee/MealsOrganizerApp/tree/mapping_many_to_many_extra_column

My DB is:

在此处输入图像描述

How can I manage this cross-table (cross-class)?

Change hibernate configuration

spring.jpa.hibernate.ddl-auto=none

by

spring.jpa.hibernate.ddl-auto=create-drop

It creates the schema and destroying previous data each time you build app. It's quite good option for initial project building.

In my opinion the best way is create db schema by Hibernate. Firstly change spring.jpa.hibernate.ddl-auto=none to spring.jpa.hibernate.ddl-auto=update or create-drop . Then remove @id annotiation in model DishIngredient on dish and ingredient column and add ReferencedColumn to @JoinColumn . Also you need add all essential methods in repo and service to model DishIngredient .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM