JPA注解中的inverse=true是什么意思?

27
在我的应用程序中,我使用Hibernate作为持久化提供程序的JPA 2.0。我有两个实体之间的一对多关系(使用@JoinColumn而不是@JoinTable)。我想知道如何在JPA注释中指定inverse=true(如在hbm.xml中指定),以反转关系所有者。
谢谢。

你到底想要实现什么? - axtavt
如您所知,inverse 可以指定关系中哪个实体负责更新外键。在我的一对多关系中,我想要明确指定这一点。https://dev59.com/hFLTa4cB1Zd3GeqPcaYa。 - Andy Dufresne
3个回答

47

我找到了答案。@OneToMany注释的mappedBy属性与xml文件中的inverse = true行为相同。


1
此外,这个问题有更多的信息:https://dev59.com/U2ct5IYBdhLWcg3wpO7H。 - SoWeLie

4

属性mappedBy表示此侧的实体是关系的反向,所有权属于另一个实体。其他实体将具有@JoinColumn注释和@ManyToOne关系。因此,我认为inverse = true与@ManyToOne注释相同。

另外,inverse = "true"表示这是关系所有者来处理关系。


3
通过使用@OneToMany@ManyToManymappedBy属性,我们可以在注解方面启用inverse="true"。例如,分支机构和员工之间存在一对多关系。
@Entity
@Table(name = "branch")
public class Branch implements Serializable {
    @Id
    @Column(name = "branch_no")
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected int branchNo;
    @Column(name = "branch_name")
    protected String branchName;
    @OneToMany(mappedBy = "branch") // this association is mapped by branch attribute of Staff, so ignore this association
    protected Set<Staff> staffSet;
    
    // setters and getters
}
@Entity
@Table(name = "staff")
public class Staff implements Serializable {
    @Id
    @Column(name = "staff_no")
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected int staffNo;
    @Column(name = "full_name")
    protected String fullName;
    @ManyToOne
    @JoinColumn(name = "branch_no", nullable = true)
    protected Branch branch;

    // setters and getters
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接