Home > Enterprise >  How to map master detail on hibernate?
How to map master detail on hibernate?

Time:10-06

enter image description here

I can not change the db schema and this is what I got so far:

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;
}

This configuration does not allow invoice_id to be duplicated on invoice_item table(it should since I can have multiple items on a given invoice)
If I make invoice_item_id composite pk I would need to add an extra column on user_invoice table which I can not.
How can I map this?

CodePudding user response:

You could split up the many-to-many association into two one-to-many associations and an entity for the join table. You can map it like this:

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;
}

  • Related