Search code examples
javahibernateone-to-manyhibernate-mapping

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:

enter image description here

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


Solution

  • 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.