I am working with JPA on a legacy database. The actual semantics are that foo owns the relationship, and that it really only has a single bar, which would require an @ManyToOne annotation.
foo (id, bar_id)
foo_bar (foo_id, bar_id)
bar (id)
Anything ending in _id is a foreign key. Also, the columns in foo_bar make up a primary key.
In an ideal world, I would just trash the foo_bar table, but there are other applications that use the same database, which might break if it’s left out. How would I map this relationship completely?
If not, what would be a good way to keep the integrity of this messy relationship?
Map the
foo.bar_idcolumn to aManyToOnerelationship. Map the join table toManyToManyrelationship. Don’t provide accessors to the collection ofbarsinFoo. Make thesetBar()clear the collection of bars and add the new one to it.This way, the ManyToMany association is completely encapsulated inside to ManyToOne association handling.