Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the JPA mappedBy attribute in a OneToMany relationship

Tags:

jpa

I am looking at examples of defining relationships between entities, and was unsure of what the mapped by in the onetomany relationship references. Is it the name of a table column, or the name of a class?

 @OneToMany(fetch = FetchType.LAZY, mappedBy = "company")
like image 277
user1154644 Avatar asked Nov 23 '25 05:11

user1154644


1 Answers

None of the above. It's the name of the attribute/property of the other side of the association. So for example:

public class Car {
    @OneToMany(mappedBy = "theCar")
    private List<Wheel> wheels;
}

public class Wheel {
    @ManyToOne
    @JoinColumn(name = "COL_CAR")
    private Car theCar;
}

In the above example, mappedBy = "theCar" means: I'm the inverse side of the bidirectional association which is mapped by the attribute theCar in the class Wheel.

And in the class Wheel, the association defines how the association is mapped: using a join column named COL_CAR.

like image 121
JB Nizet Avatar answered Nov 25 '25 17:11

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!