main
Freddy Heredia 2 years ago
parent 84670bf75f
commit 034963599e

@ -22,7 +22,6 @@ 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;
import java.lang.reflect.Field;
import java.util.Map;

@ -15,7 +15,7 @@ import pedidos.pedidos.core.producto.Producto;
public class DetallePedido {
@Id
@GeneratedValue(strategy = GenerationType.AUTO )
private Integer id;
private long id;
@ManyToOne
private Producto producto;

@ -18,14 +18,14 @@ import pedidos.pedidos.core.cliente.Cliente;
@Entity
public class Pedido {
@Id
@GeneratedValue(strategy = GenerationType.AUTO )
private Integer id;
@GeneratedValue(strategy = GenerationType.SEQUENCE )
private long id;
private String numero;
@ManyToOne
private Cliente cliente;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = false)
@JoinColumn(name="pedido_id")
private List<DetallePedido> detalle = new ArrayList<>();
}

@ -1,9 +1,13 @@
package pedidos.pedidos.core.pedidos;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
@ -16,6 +20,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.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import pedidos.pedidos.core.cliente.ClienteService;
@RestController
@RequestMapping("/api/pedido")
@CrossOrigin({"*"})
@ -23,6 +35,7 @@ public class PedidoController {
@Autowired
PedidoService service;
@Autowired ClienteService clienteService;
@GetMapping("/{id}/")
public Pedido findById(@PathVariable Integer id){
@ -52,21 +65,67 @@ public class PedidoController {
}
@PatchMapping("/{id}/")
public Pedido partialUpdate(@PathVariable Integer id, @RequestBody Map<String, Object> fields){
public Pedido partialUpdate(@PathVariable long id, @RequestBody Map<String, Object> fields){
Pedido entity = findById(id);
Pedido entity = service.findById(id);
// itera sobre los campos que se desean actualizar
for (Map.Entry<String, Object> field : fields.entrySet()) {
String fieldName = field.getKey();
Object fieldValue = field.getValue();
Object fieldValue = null;
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
java.lang.reflect.Field campoEntidad = org.springframework.util.ReflectionUtils.findField(Pedido.class, fieldName);
campoEntidad.setAccessible(true);
if (fieldName.equals("precio")){
fieldValue= new BigDecimal (field.getValue().toString());
}else if (fieldName.equals("creado")){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
fieldValue = LocalDateTime.parse(field.getValue().toString(),formatter);
}else if (fieldName.equals("detalle")){
List<?> originalList = mapper.convertValue(fields.get(fieldName), new TypeReference<List<?>>() {});
try {
Class<?> type = Class.forName("pedidos.pedidos.core.pedidos.DetallePedido");
List<Object> newList = new java.util.ArrayList<>();
for (Object o : originalList) {
newList.add(mapper.convertValue(o, type));
}
campoEntidad.set(entity,newList);
} catch(ClassNotFoundException ex) {
System.out.println("Error occuured");
ex.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
fieldValue =field.getValue();
}
// utiliza reflection para establecer el valor del campo en la entidad
try {
Field campoEntidad = Pedido.class.getDeclaredField(fieldName);
campoEntidad.setAccessible(true);
campoEntidad.set(entity, fieldValue);
} catch (NoSuchFieldException | IllegalAccessException ex) {
//Field campoEntidad = Pedido.class.getDeclaredField(fieldName);
if (campoEntidad.isAnnotationPresent(ManyToOne.class)) {
java.util.LinkedHashMap<String, Long> keyValue = mapper.convertValue(fieldValue, new TypeReference<java.util.LinkedHashMap<String, Long>>(){});
Object relatedEntity = clienteService.findById(keyValue.get("id"));
campoEntidad.set(entity, relatedEntity);
} if (campoEntidad.isAnnotationPresent(OneToMany.class)) {
//java.util.LinkedHashMap<String, Long> keyValue = mapper.convertValue(fieldValue, new TypeReference<java.util.LinkedHashMap<String, Long>>(){});
//Object relatedEntity = entidadService.findById(keyValue.get("id"));
//campoEntidad.set(entity, relatedEntity);
}
else{
//campoEntidad.set(entity, fieldValue);
campoEntidad.set(entity, mapper.convertValue(fieldValue, campoEntidad.getType()));
}
} catch ( IllegalAccessException ex) {
// maneja la excepción si ocurre algún error al acceder al campo
}
}

@ -4,7 +4,7 @@ import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface PedidoRepository extends CrudRepository <Pedido, Integer> {
public interface PedidoRepository extends CrudRepository <Pedido, Long> {
List<Pedido> findAll();
}

@ -14,11 +14,11 @@ public class PedidoService {
return repository.save(entity);
}
public void deleteById(Integer id){
public void deleteById(long id){
repository.deleteById(id);
}
public Pedido findById(Integer id){
public Pedido findById(long id){
return repository.findById(id).orElse(null);
}

@ -8,6 +8,7 @@ import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Data;
import com.fasterxml.jackson.annotation.JsonFormat;
@Data
@Entity
@ -15,11 +16,12 @@ public class Producto {
//Atributos: Delimitador de acceso, Tipo de dato, Nombre del atributo
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String nombre;
private String codigo;
private BigDecimal precio;
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm", shape = JsonFormat.Shape.STRING)
private LocalDateTime creado = LocalDateTime.now();;
}

@ -11,11 +11,21 @@ import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.lang.reflect.Field;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.persistence.ManyToOne;
@RestController
@RequestMapping("api/producto")
@CrossOrigin({"*"})
@ -50,22 +60,45 @@ public class ProductoController {
@PatchMapping("/{id}/")
public Producto partialUpdate(@PathVariable long id, @RequestBody Map<String, Object> fields){
Producto producto = findById(id);
Producto entity = findById(id);
// itera sobre los campos que se desean actualizar
for (Map.Entry<String, Object> field : fields.entrySet()) {
String fieldName = field.getKey();
Object fieldValue = field.getValue();
Object fieldValue = null;
if (fieldName.equals("precio")){
fieldValue= new BigDecimal (field.getValue().toString());
}else if (fieldName.equals("creado")){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
fieldValue = LocalDateTime.parse(field.getValue().toString(),formatter);
}else {
fieldValue =field.getValue();
}
// utiliza reflection para establecer el valor del campo en la entidad
try {
Field campoEntidad = Producto.class.getDeclaredField(fieldName);
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
//Field campoEntidad = Producto.class.getDeclaredField(fieldName);
java.lang.reflect.Field campoEntidad = org.springframework.util.ReflectionUtils.findField(Producto.class, fieldName);
campoEntidad.setAccessible(true);
campoEntidad.set(producto, fieldValue);
} catch (NoSuchFieldException | IllegalAccessException ex) {
if (campoEntidad.isAnnotationPresent(ManyToOne.class)) {
//java.util.LinkedHashMap<String, Long> keyValue = mapper.convertValue(fieldValue, new TypeReference<java.util.LinkedHashMap<String, Long>>(){});
//Object relatedEntity = entidadService.findById(keyValue.get("id"));
//campoEntidad.set(entity, relatedEntity);
}else{
//campoEntidad.set(entity, fieldValue);
campoEntidad.set(entity, mapper.convertValue(fieldValue, campoEntidad.getType()));
}
} catch ( IllegalAccessException ex) {
// maneja la excepción si ocurre algún error al acceder al campo
}
}
return update(producto);
return update(entity);
}
}
Loading…
Cancel
Save