From 84670bf75f1023c7c371c2b736e71b13c2b3a4f8 Mon Sep 17 00:00:00 2001 From: freddyheredia4 Date: Sun, 11 Jun 2023 18:16:10 -0500 Subject: [PATCH] agrega manejo de ManyToOne en path --- .../core/cliente/ClienteController.java | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/main/java/pedidos/pedidos/core/cliente/ClienteController.java b/src/main/java/pedidos/pedidos/core/cliente/ClienteController.java index 1376456..3d08e60 100644 --- a/src/main/java/pedidos/pedidos/core/cliente/ClienteController.java +++ b/src/main/java/pedidos/pedidos/core/cliente/ClienteController.java @@ -13,8 +13,14 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.fasterxml.jackson.core.type.TypeReference; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.persistence.ManyToOne; +import pedidos.pedidos.core.compania.CompaniaService; import java.math.BigInteger; import java.util.List; @@ -27,6 +33,7 @@ import java.util.Map; @Tag(name = "Controlador de Cliente (Tabla cliente)") public class ClienteController { @Autowired ClienteService clienteService; + @Autowired CompaniaService companiaService; @PreAuthorize("hasAuthority('Cliente_LeerTodos')") @GetMapping("/") @@ -68,9 +75,20 @@ public class ClienteController { // utiliza reflection para establecer el valor del campo en la entidad try { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); Field campoEntidad = Cliente.class.getDeclaredField(fieldName); campoEntidad.setAccessible(true); - campoEntidad.set(cliente, fieldValue); + + if (campoEntidad.isAnnotationPresent(ManyToOne.class)) { + java.util.LinkedHashMap keyValue = mapper.convertValue(fieldValue, new TypeReference>(){}); + Object relatedEntity = companiaService.findById(keyValue.get("id")); + campoEntidad.set(cliente, relatedEntity); + }else{ + campoEntidad.set(cliente, fieldValue); + } + + } catch (NoSuchFieldException | IllegalAccessException ex) { // maneja la excepción si ocurre algún error al acceder al campo }