diff --git a/010_spring_boot/README.md b/010_spring_boot/README.md index b9f2c3b..f0acb8f 100644 --- a/010_spring_boot/README.md +++ b/010_spring_boot/README.md @@ -10,5 +10,4 @@ Java y [JDBC](./jdbc.md) - [Curso](https://app.aluracursos.com/course/persistencia-jpa-hibernate) Persistencia con [JPA - Hibernate](./jpa_persistencia_hibernate.md) - [Curso](https://app.aluracursos.com/course/java-jpa-consultas-avanzadas-rendimiento-modelos-complejos) -[JPA](./jpa_2.avanzado.md) -consultas avanzadas, rendimiento y modelos complejos +JPA [consultas avanzadas, rendimiento y modelos complejos](./jpa_avanzado.md) diff --git a/010_spring_boot/jpa/tienda2/database/tienda.mv.db b/010_spring_boot/jpa/tienda2/database/tienda.mv.db index a46f057..ab15525 100644 Binary files a/010_spring_boot/jpa/tienda2/database/tienda.mv.db and b/010_spring_boot/jpa/tienda2/database/tienda.mv.db differ diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/CategoriaDao.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/CategoriaDao.java index 369514b..3f124a4 100644 --- a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/CategoriaDao.java +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/CategoriaDao.java @@ -35,4 +35,5 @@ public class CategoriaDao { String jpql = "SELECT P FROM Categoria AS P"; return em.createQuery(jpql, Categoria.class).getResultList(); } + } diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/PedidoDao.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/PedidoDao.java index 6504ddf..bb94100 100644 --- a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/PedidoDao.java +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/PedidoDao.java @@ -6,6 +6,7 @@ import java.util.List; import javax.persistence.EntityManager; import com.latam.alura.tienda.modelo.Pedido; +import com.latam.alura.tienda.vo.ReporteDeVenta; public class PedidoDao { @@ -51,4 +52,36 @@ public class PedidoDao { String jpql = "SELECT P.precio FROM Pedido AS P WHERE P.nombre=:nombre"; return em.createQuery(jpql, BigDecimal.class).setParameter("nombre", nombre).getSingleResult(); } + + public BigDecimal valorTotalVendido() { + String jpql = "SELECT SUM(P.valorTotal) FROM Pedido P"; + return em.createQuery(jpql, BigDecimal.class).getSingleResult(); + } + + public Double valorPromedioVendido() { + String jpql = "SELECT AVG(P.valorTotal) FROM Pedido P"; + return em.createQuery(jpql, Double.class).getSingleResult(); + } + + public List ReporteVentas() { + String jpql = "SELECT producto.nombre, SUM(item.cantidad), MAX(pedido.fecha)" + + " FROM Pedido pedido" + + " JOIN pedido.items item" + + " JOIN item.producto producto" + + " GROUP BY producto.nombre" + + " ORDER BY item.cantidad DESC"; + return em.createQuery(jpql, Object[].class).getResultList(); + } + + public List ReporteVentasVO() { + String jpql = "SELECT new com.latam.alura.tienda.vo.ReporteDeVenta(" + + "producto.nombre, SUM(item.cantidad), MAX(pedido.fecha))" + + " FROM Pedido pedido" + + " JOIN pedido.items item" + + " JOIN item.producto producto" + + " GROUP BY producto.nombre" + + " ORDER BY item.cantidad DESC"; + return em.createQuery(jpql, ReporteDeVenta.class).getResultList(); + } + } diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/ProductoDao.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/ProductoDao.java index 4688d56..79fc24e 100644 --- a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/ProductoDao.java +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/ProductoDao.java @@ -48,7 +48,6 @@ public class ProductoDao { } public BigDecimal consultaPrecioPorNombreDeProducto(String nombre) { - String jpql = "SELECT P.precio FROM Producto AS P WHERE P.nombre=:nombre"; - return em.createQuery(jpql, BigDecimal.class).setParameter("nombre", nombre).getSingleResult(); + return em.createNamedQuery("Producto.consultaDePrecio", BigDecimal.class).setParameter("nombre", nombre).getSingleResult(); } } diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Producto.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Producto.java index 0db6112..d3059f4 100644 --- a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Producto.java +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Producto.java @@ -10,10 +10,12 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity @Table(name="productos") +@NamedQuery(name="Producto.consultaDePrecio", query="SELECT P.precio FROM Producto AS P WHERE P.nombre=:nombre") public class Producto { @Id diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/prueba/RegistroDePedido.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/prueba/RegistroDePedido.java index e596c32..2b6c957 100644 --- a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/prueba/RegistroDePedido.java +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/prueba/RegistroDePedido.java @@ -1,6 +1,7 @@ package com.latam.alura.tienda.prueba; import java.math.BigDecimal; +import java.util.List; import javax.persistence.EntityManager; //import javax.persistence.EntityManagerFactory; @@ -16,6 +17,7 @@ import com.latam.alura.tienda.modelo.ItemsPedido; import com.latam.alura.tienda.modelo.Pedido; import com.latam.alura.tienda.modelo.Producto; import com.latam.alura.tienda.utils.JPAUtils; +import com.latam.alura.tienda.vo.ReporteDeVenta; public class RegistroDePedido { @@ -39,6 +41,19 @@ public class RegistroDePedido { pedidoDao.guardar(pedido); em.getTransaction().commit(); + BigDecimal valorTotal = pedidoDao.valorTotalVendido(); + System.out.println("Valor total del pedido: "+valorTotal); + Double valorPromedio = pedidoDao.valorPromedioVendido(); + System.out.println("Valor promedio del pedido: "+valorPromedio); + List reporte = pedidoDao.ReporteVentas(); + for (Object[] objects : reporte) { + System.out.print(objects[0] +", "); + System.out.print(objects[1] +", "); + System.out.println(objects[2]); + } + + List reporteVo = pedidoDao.ReporteVentasVO(); + reporteVo.forEach(System.out::println); } public static void RegistrarPedido() { diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/vo/ReporteDeVenta.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/vo/ReporteDeVenta.java new file mode 100644 index 0000000..30fe520 --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/vo/ReporteDeVenta.java @@ -0,0 +1,49 @@ +package com.latam.alura.tienda.vo; + +import java.time.LocalDate; + +public class ReporteDeVenta { + private String nombreDelProducto; + private Long cantidadDeProducto; + private LocalDate fechaDeUltimaVenta; + + public ReporteDeVenta(String nombreDelProducto, Long cantidadDeProducto, LocalDate fechaDeUltimaVenta) { + this.nombreDelProducto = nombreDelProducto; + this.cantidadDeProducto = cantidadDeProducto; + this.fechaDeUltimaVenta = fechaDeUltimaVenta; + } + + public String getNombreDelProducto() { + return nombreDelProducto; + } + + public void setNombreDelProducto(String nombreDelProducto) { + this.nombreDelProducto = nombreDelProducto; + } + + public Long getCantidadDeProducto() { + return cantidadDeProducto; + } + + public void setCantidadDeProducto(Long cantidadDeProducto) { + this.cantidadDeProducto = cantidadDeProducto; + } + + public LocalDate getFechaDeUltimaVenta() { + return fechaDeUltimaVenta; + } + + public void setFechaDeUltimaVenta(LocalDate fechaDeUltimaVenta) { + this.fechaDeUltimaVenta = fechaDeUltimaVenta; + } + + @Override + public String toString() { + return "ReporteDeVenta [" + (nombreDelProducto != null ? "nombreDelProducto=" + nombreDelProducto + ", " : "") + + (cantidadDeProducto != null ? "cantidadDeProducto=" + cantidadDeProducto + ", " : "") + + (fechaDeUltimaVenta != null ? "fechaDeUltimaVenta=" + fechaDeUltimaVenta : "") + "]"; + } + + + +} diff --git a/010_spring_boot/jpa_avanzado.md b/010_spring_boot/jpa_avanzado.md index 752d78e..2e0329a 100644 --- a/010_spring_boot/jpa_avanzado.md +++ b/010_spring_boot/jpa_avanzado.md @@ -2,7 +2,8 @@ -Retomando el proyecto [anterior](./jpa/tienda/src/main/java/com/latam/alura/tienda/) +Trabajando sobre el [proyecto](./jpa/tienda/src/main/java/com/latam/alura/tienda/) +anterior ```mermaid erDiagram @@ -18,7 +19,7 @@ erDiagram id biging PK nombre string } - Clientes ||--o{ Pedidos : tiene + Clientes ||--|{ Pedidos : tiene Clientes { id bigint PK nombre string @@ -81,7 +82,39 @@ creada anteriormente - Mapeo de nuevas entidades en la aplicación según el modelado de la base de datos -- Mapeo de una relación con cardinalidad de muchos a muchos -- Mapeo de una relación bidireccional -- Persitencia entidades que tienen relaciones bidireccionales +- Mapeo de relación con cardinalidad de muchos a muchos +- Mapeo de relación bidireccional +- Persistencia entidades que tienen relaciones bidireccionales + + +### Funciones de agregación SQL + +| Función | Descripción | +| - | - | +| **AVG** | Calcula el promedio de los valores de un campo | +| **COUNT** | Devuelve en número de registros de la selección | +| **SUM** | Devuelve la suma de todos los valores de un campo | +| **MAX** | Devuelve el valor más alto de un campo | +| **MIN** | Devuelve el valor más bajo de un campo | + +#### Reporte de ventas + +| PRODUCTO | CANT. VENDIDA | ULTIMA VENTA | +| - | :-: | - | +| Celular Motorola X9 | 240 | 01/02/23 | +| Xbox Series S | 198 | 10/02/23 | +| Framework Laptop | 71 | 20/02/2023 | + +
+ +**NamedQuerys**: Estas se declaran en la clase de entidad. + +#### Sumario Aula 2 + +- Realización de consultas utilizando funciones de agregación (**min, max, avg +y sum**) +- Consultas de reporte/informes usando JPQL +- Uso del nuevo recurso seleccionado en consultas JPQL +- Consultas mediante **NamedQuerys** +