Pavlin
Pavlin

Reputation: 5528

JPA ManyToMany mappedBy clarification

I'm learning to use JPA and there's one thing that confuses me. I'm trying to implement a many to many relationship between two classes that I've got. My database schema is simple enough. There's one table called stations (PK: station_id), one called buses (PK: bus_id) and one to connect them up together called station_bus (FKs: station_id, bus_id).

The relevant code:

// Station Class
@Entity
@Table(name = "stations")
public class Station {
    private List<Bus> buses;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "station_bus",
            joinColumns = {@JoinColumn(name = "bus_id")},
            inverseJoinColumns = {@JoinColumn(name = "station_id")}
    )
    public List<Bus> getBuses() { return buses; }
}

// Bus Class
@Entity
@Table(name = "buses")
public class Bus {
    private List<Station> stations;

    @ManyToMany(
            fetch = FetchType.LAZY,
            mappedBy = "buses"
    )
    public List<Station> getStations() { return stations; }
}

There is one thing that confuses me. I understand that in a many to many relationship, one needs to be the owner, Station in this case, and one the ownee. The difference being the owner needs to specify the @JoinTable annotation and the ownee needing to specify mappedBy. The thing I don't understand is what the mappedBy value needs to be set to.

From what I gather from the various examples I've looked over is that it needs to be the name of the field in the owner class, so in this example, since Station contains a buses field, that's what the mapped by needs to be set to.

If anybody could confirm or correct me, it would be helpful, as I haven't been able to find an answer.

Upvotes: 2

Views: 986

Answers (1)

Ish
Ish

Reputation: 4154

Some notes:

The absence of the mappedBy element in the mapping annotation implies ownership of the relationship, while the presence of the mappedBy element means the entity is on the inverse side of the relationship.

The value of mappedBy is the name of the attribute in the owning entity that points back to the inverse entity.

Your sample use of mappedBy is correct.

Upvotes: 3

Related Questions