public class Invoice {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
// Some fields ...
@ToString.Exclude
@JsonIgnore
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "invoice_elements",
joinColumns = @JoinColumn(name = "invoice_id"),
inverseJoinColumns = @JoinColumn(name = "element_id")
)
private List<CostElements> costElements;
}
public class CostElements {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@ToString.Exclude
@JsonIgnore
@ManyToMany(mappedBy = "costElements")
private List<Invoice> invoices;
}
// InvoiceRequest Dto has both invoice data and cost elements data.
@Override
public void saveInvoice(InvoiceRequest invoiceRequest) {
CostElements costElement1 = new CostElements();
costElement1.setName(invoiceRequest.getName());
costElement1.setInvoices();
CostElements costElement2 = new CostElements();
costElements2.setName(invoiceRequest.getName());
costElements2.setInvoices();
List<CostElements> elementList = new ArrayList<>();
elementList.add(costElement1);
elementList.add(costElement2);
Invoice invoice = new Invoice();
invoice.setCostElements(elementList);
}
Look at the saveInvoice()
method. My question is how should I save costElements
and Invoice
correctly. How can I handle these setter methods correctly ? -> costElement1.setInvoices(); costElements2.setInvoices();
Because even though there is a setter method called -> setInvoices();
But we have only one Invoice
. Can anyone please clarify this problem for me ?
I tried this;
for (CostElements costElement : elementList) {
costElement.getInvoices().add(invoice);
}
But it is not working as I expected.