vladmihalcea / high-performance-java-persistence

The High-Performance Java Persistence book and video course code examples
Apache License 2.0
1.31k stars 489 forks source link

Error when changing to OneToOne relationship #29

Closed cca-developer closed 6 years ago

cca-developer commented 6 years ago

This test works fine with a ManyToOne/OneToMany relationship between PostTag and Tag. However, if that is changed to a OneToOne relationship, the test no longer passes.

vladmihalcea commented 6 years ago

Why would you change it to OneToOne? This is a many-to-many association. Do you want to map a one-to-one association with an intermediary table?

cca-developer commented 6 years ago

I have a situation where I have WorkOrders and Inspections. A WorkOrder can have many Inspections attached to it, but an Inspection can only be attached to one WorkOrder. Also, a WorkOrder may not have any inspections. If a WorkOrder has one or more inspections, there needs to be some extra information attached to each inspection, which I why I want the extra join table. But it is not a straight one-to-one association because a WorkOrder could have many inspections. If I didn't need the extra information, this would obviously be really easy. I could make it look like a many-to-many association, but that is somewhat confusing because an Inspection entity would never have a list of associated work orders. Does that use case make sense?

vladmihalcea commented 6 years ago

A One-to-one child association cannot have a OneToMany on the other side. It can have a One-to-one.

cca-developer commented 6 years ago

Sorry, I just realized that I had only changed the relationship on your code and hadn't changed anything else. Does it make more sense now what I am trying to do? Sorry about that!

cca-developer commented 6 years ago

The test now successfully passes. I'm not sure why it is not working on my code. Does this seem like a legitimate way to set up a relationship now?

cca-developer commented 6 years ago

I did finally get this to work in my program. I had been thinking that the MapsId annotations were referring to a database field, not a property in the PostTagId class. I'm still curious on your thoughts about this relationship. Thanks!

vladmihalcea commented 6 years ago

I'm glad you found the solution. As for the mapping, I never had to use it. Probably you can simplify it to a OneToMany association and merge the two one-to-one sides.