Код: Выделить всё
@Entity
public class Venta {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "numero")
private Integer numeroComprobante;
@Column(name = "fecha_venta")
private LocalDateTime fecha;
@Column()
private String nombreCliente;
@OneToMany(mappedBy = "venta", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private List detalles;
...
}
@Entity
@Table(name = "venta_detalle")
public class Detalle {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Double cantidad;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "venta_id")
private Venta venta;
@ManyToOne
@JoinColumn(name = "producto_id", referencedColumnName = "id")
private Producto producto;
}
@Entity
public class Producto {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nombre;
private String descripcion;
private Double precio;
private LocalDateTime fechaAlta;
@JsonIgnore
@OneToMany(mappedBy = "producto", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List detalles;
}
Код: Выделить всё
public VentaResponse update(Long id, VentaRequest ventaRequest) {
Optional venta = this.ventaRepository.findById(id);
if (venta.isEmpty())
throw new ProcesoException("Venta con ID " + id + " no existe.");
venta.get().setNombreCliente(ventaRequest.getNombreCliente());
for (Detalle detalle: venta.get().getDetalles())
this.detalleRepository.delete(detalle);
List detalles = new ArrayList();
Detalle detalle;
Optional
producto;
for (DetalleRequest detalleRequest: ventaRequest.getDetalles()) {
detalle = new Detalle();
producto = this.productoRepository.findById(detalleRequest.getProductoId());
if (producto.isEmpty())
throw new ProcesoException("Producto con ID " + detalleRequest.getProductoId() + "no encontrado.");
detalle.setCantidad(detalleRequest.getCantidad());
detalle.setVenta(venta.get());
detalle.setProducto(producto.get());
detalles.add(detalle);
}
venta.get().setDetalles(detalles);
Venta ventaActualizada = this.ventaRepository.save(venta.get());
return this.convertirVentaAVentaResponse(ventaActualizada);
}
Коллекция с cascade="all-delete-orphan" больше не
ссылался экземпляр объекта-владельца:
net.comercial.ventas.ventas.Venta.detalles
Что я пробовали:
- Изменить orphanRemoval в Венте на false
- Изменить конфигурацию каскада или Правило удаления и Правило обновления для Отношения Venta-Detalle в Postgres с Cascade
- Удаление деталей, связанных с Venta, перед обновлением Venta и ее новых деталей
Подробнее здесь: https://stackoverflow.com/questions/788 ... lationship
Мобильная версия