使用结点表的JPA I:N和1:1 [英] JPA I:N and 1:1 using Junction table

查看:168
本文介绍了使用结点表的JPA I:N和1:1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JPA问题:我正在尝试使用联结表(Person_Address)对1:N(人与地址)关系进行建模.

JPA Question: I am trying to model 1:N (Person & Address) relationship using a junction table (Person_Address).

  1. 人(personId PK)

  1. Person (personId PK)

地址(addressId PK)

Address (addressId PK)

PersonAddress( personId,addressId复合PK, personId FK引用Person, addressid FK引用地址)

PersonAddress ( personId, addressId composite PK, personId FK references Person, addressid FK references Address)

如何映射这些关系?加载Person对象时如何加载地址列表?

How to map these relationships? How to load list of addresses when Person object is loaded?

推荐答案

您正在描述一个OneToMany关系,该关系通常不需要联接表.您仅在多"一面有一个引用一"面的字段.

You're describing a OneToMany relationship which typically does not require a join table. You just have a field on the Many side that references the One side.

但是,如果您确实想做自己正在做的事情,那么这应该可行:

However, if you really want to do what you're doing, then this should work:

@Entity
public class Person {

...

  @OneToMany
  @JoinTable(
    name="PersonAddress",
    joinColumns = @JoinColumn( name="personId"),
    inverseJoinColumns = @JoinColumn( name="addressId")
   )
  public Set<Address> getAddresses() {...}

...
}

这篇关于使用结点表的JPA I:N和1:1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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