jpa 如何在Hibernate上Map主详细信息?

ryevplcw  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(125)

我无法更改数据库模式,这是我目前得到的结果:

public class User{
  @Id
  private String userId;
  @OneToMany
  @JoinTable(
       name = "user_invoice",
       joinColumns = @JoinColumn(name="user_id"),
       inverseJoinColumns = @JoinColumn(name = "invoice_id")
  )
  private List<InvoiceItem> invoiceItems;
}

public class InvoiceItem{
  @Id
  private String invoiceId;
  private String invoiceItemId;
}

此配置不允许invoice_id在invoice_item表中重复(应该如此,因为在给定发票上可以有多个项目)
如果生成invoice_item_id复合pk,则需要在user_invoice表中添加一个额外的列,但我无法添加。
如何Map此内容?

b5buobof

b5buobof1#

您可以将多对多关联拆分为两个一对多关联和一个用于联接表的实体。您可以按如下方式进行Map:

public class User{
  @Id
  private String userId;
  @OneToMany(mappedBy = "user")
  private List<Invoice> invoices;
}
@Table(name = "user_invoice")
public class Invoice{
  @Id
  @ManyToOne(fetch = LAZY)
  @JoinColumn(name="user_id")
  private User user;
  @Id
  private String invoiceId;
  @OneToMany(mappedBy = "invoice")
  private List<InvoiceItem> invoiceItems;
}

public class InvoiceItem{
  @Id
  @ManyToOne(fetch = LAZY)
  private Invoice invoice;
  @Id
  private String invoiceItemId;
}

相关问题