springhibernatejpaone-to-manyrelational

Spring: weird onetomany mapping with relational table for each relation


I'm trying to build a number of relations the way i've been told to. I have 6 tables...let's call them A, B, C, D, E and F.

The relation between them is always 1:N.

I've been asked to map those tables in Spring/JPA by creating a new relational table each time like so:

A + B -> AB
AB + C -> ABC
ABC + D -> ABCD
ABCD + E -> ACBDE
ACBDE + F -> ABCDEF

...where AB, ABC, ACBD, ABCDE and ACBDEF are the new relational tables I have to create.

It feels so weird to me to map tables like so, even more when the relation betweed them is not N:N, but 1:N. Also, I don't get to see the purpose ot donig that, and I came here to see if you guys could help me with both issues: Understanding why this would make sense, and how to achieve this?

I've tried myself for 2 days, but mapping the tables like they were N:N, and I always get an error like "Caused by: org.hibernate.MappingException: Foreign key (FKsxjpculqrp0noj2x8cetijcof:CEV_ambito [id_amb])) must have same number of columns as the referenced primary key (CEV_ambito [FK_tea_amb,id_amb])"

Please, any help or indications on how to do this properly would be really appreciated. Thank you all.


Solution

  • this is indeed a weird requirement (might make more sense if we knew about the data inside of those tables) but anyways to get 1:N you should use a foreign key inside of the next table so B has foreign key to A, C has foreignkey pointing at B and so forth.

    Hibernate (jpa) by default will use a separate intermediary table for mapping which makes it look like many to many but you can customize this behavior with @JoinColumn like shown here

    https://www.baeldung.com/jpa-join-column#oneToMany_mapping