Whimusical Whimusical - 1 month ago 7
Java Question

@OneToMany by means of mappedBy without @JoinColumns

I am founding some legacy code in my job where some of the following shows up:

For simplification, imagine a One class and a Many class.
In One Class I got:

@OneToMany(mappedBy = "toOne")
private List<Many> manies;

But in Many class, the field toOne is defined as:

@JoinColumn(name = "unrelated", referencedColumnName = "id")
UnrelatedEntity toOne;

The only plausible explanation is that toOne field has both a relation with Unrelated and also a FK to Many. But, is it possible to have a @OneToMany using mappedBy without the use of a local or remote @JoinColumn? I did not see any example using that simplification. Is it using One.@Id for the join automagically?


"mappedBy" links the 2 sides of the relation nothing more. If you omit the JoinColumn then it will use a join table to manage the relation. If you use JoinColumn then it manages the relation via an FK in the "many side". Very simple. It will use how many @Id fields there are in the "1 side" for the FK.