简体   繁体   English

JPA ManyToMany映射通过澄清

[英]JPA ManyToMany mappedBy clarification

I'm learning to use JPA and there's one thing that confuses me. 我正在学习使用JPA,有一件事使我感到困惑。 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) . 有一个表叫做stations(PK: station_id) ,一个表叫做buss(PK:bus_id),还有一个将它们连接在一起的表称为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. 我了解,在多对多关系中,一个必须是所有者(在这种情况下为Station)和一个所有者。 The difference being the owner needs to specify the @JoinTable annotation and the ownee needing to specify mappedBy . 所不同的是车主需要指定@JoinTable注解和ownee需要指定mappedBy The thing I don't understand is what the mappedBy value needs to be set to. 我不明白的是,需要将mappedBy值设置为什么。

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. 从我查看的各个示例中收集到的信息来看,它必须是所有者类中字段的名称,因此在此示例中,由于Station包含buss字段,因此需要设置映射者至。

If anybody could confirm or correct me, it would be helpful, as I haven't been able to find an answer. 如果有人可以确认或纠正我,这将有所帮助,因为我无法找到答案。

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. 映射批注中缺少mapledBy元素意味着该关系的所有权,而mapledBy元素的存在意味着该实体位于关系的反面。

The value of mappedBy is the name of the attribute in the owning entity that points back to the inverse entity. mappedBy的值是拥有实体中指向反向实体的属性的名称。

Your sample use of mappedBy is correct. 您对mappedBy的示例用法是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM