Reputation: 1
I'm getting some problems with a API with 2 relations.
Model - coche
@Data
@Entity
@Table(name = "coches")
public class Coche {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String matricula;
private String modelo;
private String color;
private boolean reservado=false;
@Enumerated(EnumType.STRING)
private NivelGasolina nivelGasolina;
@OneToMany(mappedBy = "coche")
@JsonBackReference
private List<Booking> bookings;
public Long getId() {
return id;
}
}
Model - Booking
@Data
@Entity
@Table(name = "booking")
public class Booking {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private Integer roomNumber;
// Serializa las fechas en el formato "día/mes/año"
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private LocalDate fechaInicio;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private LocalDate fechaFin;
@ManyToOne
@JoinColumn(name = "coche_id" /* , nullable = false*/)
@JsonManagedReference
private Coche coche;
}
Controller - Booking
@RestController
@RequestMapping("/api/booking")
@RequiredArgsConstructor
public class BookingController {
private final BookingService bookingService;
@GetMapping
public ResponseEntity<List<Booking>> obteinAllBookings() {
return ResponseEntity.ok(bookingService.obteinallBookings());
}
@PostMapping
public ResponseEntity<Booking> createNewBooking(@RequestBody Booking booking) {
try {
Booking createdBooking = bookingService.newBooking(booking);
return ResponseEntity.status(HttpStatus.CREATED).body(createdBooking);
} catch (Exception e) {
System.out.println("Error al crear la reserva : ---->> " + e.getMessage()); // Imprime el mensaje de error en la consola
e.printStackTrace(); // Imprime el stack trace del error
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
}
Service - Booking
public class BookingService {
private final BookingRepository bookingRepository;
private final CocheRepository cocheRepository;
public List<Booking> obteinallBookings() {
return bookingRepository.findAll();
}
public Booking newBooking(Booking booking) {
if (booking.getCoche() != null && booking.getCoche().getId() != null) {
Coche cocheExistente = cocheRepository.findById(booking.getCoche().getId())
.orElseThrow(() -> new RuntimeException("Coche no encontrado"));
booking.setCoche(cocheExistente);
cocheExistente.setReservado(true);
}
return bookingRepository.save(booking);
}
public Booking updateBooking(Long id, Booking booking) {
Booking existBooking = bookingRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Booking no encontrado"));
existBooking.setFechaInicio(booking.getFechaInicio());
existBooking.setFechaFin(booking.getFechaFin());
return bookingRepository.save(existBooking);
}
public void deteleBooking(Long id) {
bookingRepository.deleteById(id);
}
}
The problems its;
'coches' works fine with postman, I can get/update/delete, I had some data in the data.sql, some cars and 1 booking.
When I try GET on booking API works fine, I get this;
{
"id": 1,
"roomNumber": 101,
"fechaInicio": "01-10-2023",
"fechaFin": "05-10-2023",
"coche": {
"id": 1,
"matricula": "1234ABC",
"modelo": "Toyota Corolla",
"color": "#808080",
"reservado": true,
"nivelGasolina": "LLENO"
}
}
]
But if I try to POST on booking with this JSON;
{
"roomNumber": 182,
"fechaInicio": "2023-10-05",
"fechaFin": "2023-10-08",
"coche": {
"id": 4
}
}
I get this error;
2024-12-16T16:58:18.664Z WARN 17972 --- [LucasRent] [nio-8080-exec-3] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.lucas.fuel.LucasRent.model.Booking]]
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (`java.util.List<com.lucas.fuel.LucasRent.model.Booking>`) not compatible with managed type (com.lucas.fuel.LucasRent.model.Booking)
I dont know where is the problem, on postman I had tried to Header -> Content-type -> application/json but it dont works anyways..
I tried a lot, since types of consume json on the code...
Upvotes: 0
Views: 33