JoinColumn和mappedBy之间有什么区别

JoinColumn和mappedBy之间有什么区别

本文介绍了使用JPA @OneToMany关联时@JoinColumn和mappedBy之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

@Entity
public class Company {

    @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY)
    @JoinColumn(name = "companyIdRef", referencedColumnName = "companyId")
    private List<Branch> branches;
    ...
}

@Entity
public class Company {

    @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY, mappedBy = "companyIdRef")
    private List<Branch> branches;
    ...
}


推荐答案

@JoinColumn 可用于关系的双方。问题是关于使用 @JoinColumn @OneToMany 一侧(极少数情况下)。这里的重点是物理信息重复(列名)以及未优化的SQL查询,它将产生一些额外的UPDATE语句

@JoinColumn could be used on both sides of the relationship. The question was about using @JoinColumn on the @OneToMany side (rare case). And the point here is in physical information duplication (column name) along with not optimized SQL query that will produce some additional UPDATE statements.

根据:

由于多对一(几乎)始终是JPA规范中双向关系的所有者方,因此会对一对多关联进行注释by @OneToMany(mappedBy = ...)

Since many to one are (almost) always the owner side of a bidirectional relationship in the JPA spec, the one to many association is annotated by @OneToMany(mappedBy=...)

@Entity
public class Troop {
    @OneToMany(mappedBy="troop")
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk")
    public Troop getTroop() {
    ...
}

部队通过部队属性与士兵有一对一的双向关系。您不必(不得)在mappedBy端定义任何物理映射。

Troop has a bidirectional one to many relationship with Soldier through the troop property. You don't have to (must not) define any physical mapping in the mappedBy side.

要将双向的映射到多个,使用 one-to - 很多方面作为拥有方,您必须删除mappedBy元素并将多个@JoinColumn设置为可插入且可更新为false。此解决方案未经过优化,将生成一些额外的UPDATE语句。

To map a bidirectional one to many, with the one-to-many side as the owning side, you have to remove the mappedBy element and set the many to one @JoinColumn as insertable and updatable to false. This solution is not optimized and will produce some additional UPDATE statements.

@Entity
public class Troop {
    @OneToMany
    @JoinColumn(name="troop_fk") //we need to duplicate the physical information
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk", insertable=false, updatable=false)
    public Troop getTroop() {
    ...
}

这篇关于使用JPA @OneToMany关联时@JoinColumn和mappedBy之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:40