在Jpa中一对多映射 [英] Multiple mapping One to many in Jpa

查看:195
本文介绍了在Jpa中一对多映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在单个实体A中与实体B(注释为一对多)存在多种关系(多对一)?我必须为B中每次出现的A都添加一个注释吗?

If I've, in a single entity A, multiple relations (many to one) towards an entity B (annotated with one to many)? Do I've to put an annotation for each occurrence of A in B?

示例:

实体A:

@Entity
@Table(name = "patient")
@TableGenerator(name = "tab_gen_pa", initialValue = 30000, allocationSize = 1)
public class Patient implements Serializable, Comparable<Patient> {

 @ManyToOne
    @Column(name = "birth_region")
    private Region birthRegion;

    @ManyToOne
    @Column(name = "birth_province", length = 2)
    private Province birthProvince;

    @ManyToOne
    @Column(name = "birth_municipality")
    private Municipality birthMunicipality;

@Column(name = "living_region")
    @ManyToOne
    private Region livingRegion;

    @Column(name = "living_province", length = 2)
    @ManyToOne
    private Province livingProvince;

    @Column(name = "living_municipality")
    @ManyToOne
    private Municipality livingMunicipality;

实体B:例如区域:

@Entity
@Table(name = "region")
@TableGenerator(name = "tab_gen_re", initialValue = 30, allocationSize = 1)
public class Region implements Serializable {

@OneToMany(mappedBy = "livingRegion")
    private List<Patient> patients;

我是否也要在Region中插入

Do I've to insert also in Region:

@OneToMany(mappedBy = "birthRegion")
        private List<Patient> patientsBirthRegion;

??

推荐答案

下面的一对关联映射,

@ManyToOne
@Column(name = "birth_region")
private Region birthRegion;


@OneToMany(mappedBy = "birthRegion")
private List<Patient> patientsBirthRegion;  

仅在patient列表和它们的birthRegion之间定义bidirectional association.现在,如果您想要这些区域中其他regionspatients之间的关联类型相似,则需要在它们之间具有这种类型的关联映射.

defines the bidirectional association only between a list of patients and their birthRegion. Now if you want similar type of associations between other regions and the patients in those regions, you need to have this type of association mappings among them.

这篇关于在Jpa中一对多映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆