I'm implementing a master-detail relationship and I'm having troubles when persisting data. I defined the following classes to represent the relationship:
`// MASTER
@Entity
@Table(name = "factura_cabecera")
public class FacturaEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long numeroFactura;
private LocalDateTime fechaEmision;
private String nombreRazonSocial;
private String codigoCliente;
private BigDecimal montoTotal;
private String usuario;
@OneToMany(
mappedBy = "factura",
cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE },
fetch = FetchType.LAZY,
orphanRemoval = true
)
private List<FacturaDetalleEntity> detalleList;
}
// DETAIL
@Entity
@Table(name = "factura_detalle")
public class FacturaDetalleEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 500)
private String descripcion;
private BigDecimal cantidad;
private Integer unidadMedida;
private BigDecimal precioUnitario;
private BigDecimal subTotal;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "id_factura", referencedColumnName = "id")
private FacturaEntity factura;
}`
I've also defined some classes to represent the request to the API and I'm using them this way to fill factura (master) and detalle (detail):
`FacturaEntity factura = new FacturaEntity();
// filling factura properties
factura.setNumeroFactura(facturaElectronicaCompraVenta.getCabecera().getNumeroFactura());
...
// filling detalle properties
List<DetalleCompraVenta> detalleList = facturaElectronicaCompraVenta.getDetalle();
List<FacturaDetalleEntity> facturaDetalleList = new ArrayList<>();
for (DetalleCompraVenta detalle :detalleList) {
facturaDetalleList.add(detalle);
}
factura.setDetalleList(facturaDetalleList);
// persist data
facturaRepository.save(factura);`