I am making a REST api in Java with Spring boot JPA Hibernate and with H2 database, I am trying to do a POST to "api/facturas" which is the RequestMapping of FacturaController, in which I want to add data to the FacturaDetalles List, but It returns an empty array, as if the data had never been sent, what am I doing wrong here?
I am trying to make a POST to " /api/facturas " like this:
{
"cliente": {
"idCliente": 1
},
"facturaDetalles": [
{
"producto": {
"idProducto": 3
}
}
]
}
This is what it should return:
{
"cliente": {
"idCliente": 1,
"nombreCliente": "Juan",
"apellidoCliente": "Rufiol",
"dni": 35884121,
"direccionCliente": "Av. Siempre Viva 300",
"telefonoCliente": 353654128,
"emailCliente": "juancito@gmail.com",
"cuit": 5412456985510,
"ciudad": "Capital Federal",
"provincia": "Buenos Aires",
"pais": "Argentina",
"codigoPostal": 1426,
"fechaNacimiento": "10-10-1980"
},
"facturaDetalles": [
{
"idFacturaDetalles": 1,
"producto": {
"idProducto": 3,
"nombreProducto": "Pollo frito",
"precioProducto": 40,
"descripcion": "Una delicia king chicken",
"stock": 3
}
}
]
}
This is what i get:
{
"cliente": {
"idCliente": 1,
"nombreCliente": "Juan",
"apellidoCliente": "Rufiol",
"dni": 35884121,
"direccionCliente": "Av. Siempre Viva 300",
"telefonoCliente": 353654128,
"emailCliente": "juancito@gmail.com",
"cuit": 5412456985510,
"ciudad": "Capital Federal",
"provincia": "Buenos Aires",
"pais": "Argentina",
"codigoPostal": 1426,
"fechaNacimiento": "10-10-1980"
},
"facturaDetalles": []
}
[data.sql]
INSERT INTO clientes (nombre,apellido,dni,direccion,telefono,email,cuit,ciudad,provincia,pais,codigo_postal, fecha_nacimiento ) VALUES ('Juan','Rufiol','35884121','Av. Siempre Viva 300','353654128','juancito@gmail.com','5412456985510','Capital Federal','Buenos Aires', 'Argentina',1426,'10-10-1980' );
INSERT INTO clientes (nombre,apellido,dni,direccion,telefono,email,cuit,ciudad,provincia,pais,codigo_postal, fecha_nacimiento ) VALUES ('Rolo','Garcia','41882121','Mariano Moreno 44','353614128','rolaso@rol.com','51134569854113','Capital Federal','Buenos Aires', 'Argentina',1426,'01-03-1989' );
INSERT INTO facturas (nro_factura,tipo_factura,precio_total_factura,id_cliente) VALUES (4444,'A',2000,1);
INSERT INTO facturas (nro_factura,tipo_factura,precio_total_factura,id_cliente ) VALUES (4444,'A',2000,1);
INSERT INTO facturas_detalles (cantidad,subtotal,id_facturas ,id_producto) VALUES (1,1,1,3);
INSERT INTO facturas_detalles (cantidad,subtotal,id_facturas ,id_producto) VALUES (1,1,1,2);
[Factura]
@Entity
@Table(name = "facturas")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Factura {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long idFactura;
@Column(name = "nro_factura")
private Integer nroFactura;
@Column(name = "tipo_factura")
private String tipoFactura;
@Column(name = "fecha", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private String fechaFactura;
@Column(name = "precio_total_factura")
private Integer precioTotalFactura;
@OneToOne
@JoinColumn(name = "id_cliente")
private Cliente cliente;
@JsonManagedReference
@OneToMany(mappedBy = "factura", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<FacturaDetalles> facturaDetalles = new ArrayList<>();
@OneToOne
@JoinColumn(name = "id_empresa")
private Empresa empresa;
}
[FacturaDTO]
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FacturaDTO {
private ClienteDTO cliente;
private List<FacturaDetallesDTO> facturaDetalles;
}
[FacturaServiceImp]
@Service
public class FacturaServiceImp implements FacturaService {
@Autowired
private FacturaRepository facturaRepository;
public List<Factura> getAllFacturas() {
return facturaRepository.findAll();
}
public Factura getOneFactura(Long id) {
return facturaRepository.findById(id).orElseThrow(() -> new RuntimeException("Factura no encontrado"));
}
public Factura createFactura(Factura factura) {
return facturaRepository.save(factura);
}
public void deleteFactura(Long id) {
facturaRepository.deleteById(id);
}
}
[FacturaService]
public interface FacturaService {
List<Factura> getAllFacturas();
Factura getOneFactura(Long id);
Factura createFactura(Factura factura);
void deleteFactura(Long id);
}
[FacturaController]
@RestController
@RequestMapping("/api/facturas")
public class FacturaController {
@Autowired
ModelMapper modelMapper;
@Autowired
FacturaService facturaService;
@GetMapping()
public List<FacturaDTO> getAllFacturas() {
return facturaService.getAllFacturas().stream().map(factura -> modelMapper.map(factura, FacturaDTO.class)).collect(Collectors.toList());
}
@GetMapping("/{id}")
public ResponseEntity<FacturaDTO> getOneFactura(@PathVariable Long id) {
Factura factura = facturaService.getOneFactura(id);
FacturaDTO facturaDTO = modelMapper.map(factura, FacturaDTO.class);
return ResponseEntity.ok().body(facturaDTO);
}
@PostMapping()
public ResponseEntity<FacturaDTO> createFactura(@RequestBody FacturaDTO facturaDTO) {
Factura factura = modelMapper.map(facturaDTO, Factura.class);
Factura facturaCreacion = facturaService.createFactura(factura);
FacturaDTO conversion = modelMapper.map(facturaCreacion, FacturaDTO.class);
return new ResponseEntity<FacturaDTO>(conversion, HttpStatus.CREATED);
}
@DeleteMapping("/{id}")
public ResponseEntity<FacturaDTO> deleteFactura(@PathVariable Long id) {
Factura factura = facturaService.getOneFactura(id);
facturaService.deleteFactura(id);
FacturaDTO facturaDTO = modelMapper.map(factura, FacturaDTO.class);
return ResponseEntity.ok().body(facturaDTO);
}
}
[FacturaDetalles]
@Entity(name = "facturas_detalles")
@Table(name = "facturas_detalles")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FacturaDetalles {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long idFacturaDetalles;
@Column(name = "cantidad")
private Integer cantidadProductos;
@Column(name = "subtotal")
private Integer totalParcial;
@JsonBackReference
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_facturas")
private Factura factura;
@OneToOne
@JoinColumn(name = "id_producto")
private Producto producto;
}
[FacturaDetallesDTO]
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FacturaDetallesDTO {
private Long idFacturaDetalles;
private ProductoDTO producto;
}
[FacturaDetallesServiceImp]
@Service
public class FacturaDetallesServiceImp implements FacturaDetallesService {
@Autowired
private FacturaDetallesRepository facturaDetallesRepository;
public List<FacturaDetalles> getAllFacturaDetalles() {
return facturaDetallesRepository.findAll();
}
public FacturaDetalles getOneFacturaDetalles(Long id) {
return facturaDetallesRepository.findById(id).orElseThrow(() -> new RuntimeException("Factura no encontrado"));
}
public FacturaDetalles createFacturaDetalles(FacturaDetalles facturaDetalles) {
return facturaDetallesRepository.save(facturaDetalles);
}
public void deleteFacturaDetalles(Long id) {
facturaDetallesRepository.deleteById(id);
}
}
[FacturaDetallesService]
public interface FacturaDetallesService {
List<FacturaDetalles> getAllFacturaDetalles();
FacturaDetalles getOneFacturaDetalles(Long id);
void deleteFacturaDetalles(Long id);
FacturaDetalles createFacturaDetalles(FacturaDetalles facturaDetalles);
}
[FacturaDetallesController]
@RestController
@RequestMapping("/api/detalles")
public class FacturaDetallesController {
@Autowired
ModelMapper modelMapper;
@Autowired
FacturaDetallesService facturaDetallesService;
@GetMapping()
public List<FacturaDetallesDTO> getAllFacturaDetalles() {
return facturaDetallesService.getAllFacturaDetalles().stream().map(facturaDetalles -> modelMapper.map(facturaDetalles, FacturaDetallesDTO.class)).collect(Collectors.toList());
}
@GetMapping("/{id}")
public ResponseEntity<FacturaDetallesDTO> getOneFacturaDetalles(@PathVariable Long id) {
FacturaDetalles facturaDetalles = facturaDetallesService.getOneFacturaDetalles(id);
FacturaDetallesDTO detallesDTO = modelMapper.map(facturaDetalles, FacturaDetallesDTO.class);
return ResponseEntity.ok().body(detallesDTO);
}
@PostMapping()
public ResponseEntity<FacturaDetallesDTO> createFacturaDetalles(@RequestBody FacturaDetallesDTO facturaDetallesDTO) {
FacturaDetalles facturaDetalles = modelMapper.map(facturaDetallesDTO, FacturaDetalles.class);
FacturaDetalles facturaDetallesCreacion = facturaDetallesService.createFacturaDetalles(facturaDetalles);
FacturaDetallesDTO conversion = modelMapper.map(facturaDetallesCreacion, FacturaDetallesDTO.class);
return new ResponseEntity<FacturaDetallesDTO>(conversion, HttpStatus.CREATED);
}
@DeleteMapping("/{id}")
public ResponseEntity<FacturaDetallesDTO> deleteFacturaDetalles(@PathVariable Long id){
FacturaDetalles facturaDetalles = facturaDetallesService.getOneFacturaDetalles(id);
facturaDetallesService.deleteFacturaDetalles(id);
FacturaDetallesDTO detallesDTO = modelMapper.map(facturaDetalles, FacturaDetallesDTO.class);
return ResponseEntity.ok().body(detallesDTO);
}
}
try like this (lines omitted due to readability, eg checks)
@Autowired
private FacturaRepository facturaRepository;
@Autowired
private FacturaDetallesRepository facturaDetallesRepository;
public Factura createFactura(...) {
// get factura from db (by id from dto)
Factura factura = facturaRepository.findByIdFactura(facura.getIdFactura())
// get facturaDetalles from db (by id from dto)
FacturaDetalles facturaDetalles = facturaDetallesRepository.findByIdFacturaDetalles(...)
// link entites, for each detalles object!
facturaDetalles.setFactura(factura)
// add to list, but check if already in list first
factura.getFacturaDetalles().add(facturaDetalles)
facturaRepository.save(factura);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.