JPA Consultas avanzadas...: Aula 2

This commit is contained in:
devfzn 2023-09-06 19:59:09 -03:00
parent d41f0f89bd
commit fdb82ae7f9
Signed by: devfzn
GPG Key ID: E070ECF4A754FDB1
9 changed files with 140 additions and 9 deletions

View File

@ -10,5 +10,4 @@ Java y [JDBC](./jdbc.md)
- [Curso](https://app.aluracursos.com/course/persistencia-jpa-hibernate) - [Curso](https://app.aluracursos.com/course/persistencia-jpa-hibernate)
Persistencia con [JPA - Hibernate](./jpa_persistencia_hibernate.md) Persistencia con [JPA - Hibernate](./jpa_persistencia_hibernate.md)
- [Curso](https://app.aluracursos.com/course/java-jpa-consultas-avanzadas-rendimiento-modelos-complejos) - [Curso](https://app.aluracursos.com/course/java-jpa-consultas-avanzadas-rendimiento-modelos-complejos)
[JPA](./jpa_2.avanzado.md) JPA [consultas avanzadas, rendimiento y modelos complejos](./jpa_avanzado.md)
consultas avanzadas, rendimiento y modelos complejos

View File

@ -35,4 +35,5 @@ public class CategoriaDao {
String jpql = "SELECT P FROM Categoria AS P"; String jpql = "SELECT P FROM Categoria AS P";
return em.createQuery(jpql, Categoria.class).getResultList(); return em.createQuery(jpql, Categoria.class).getResultList();
} }
} }

View File

@ -6,6 +6,7 @@ import java.util.List;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import com.latam.alura.tienda.modelo.Pedido; import com.latam.alura.tienda.modelo.Pedido;
import com.latam.alura.tienda.vo.ReporteDeVenta;
public class PedidoDao { public class PedidoDao {
@ -51,4 +52,36 @@ public class PedidoDao {
String jpql = "SELECT P.precio FROM Pedido AS P WHERE P.nombre=:nombre"; String jpql = "SELECT P.precio FROM Pedido AS P WHERE P.nombre=:nombre";
return em.createQuery(jpql, BigDecimal.class).setParameter("nombre", nombre).getSingleResult(); 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<Object[]> 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<ReporteDeVenta> 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();
}
} }

View File

@ -48,7 +48,6 @@ public class ProductoDao {
} }
public BigDecimal consultaPrecioPorNombreDeProducto(String nombre) { public BigDecimal consultaPrecioPorNombreDeProducto(String nombre) {
String jpql = "SELECT P.precio FROM Producto AS P WHERE P.nombre=:nombre"; return em.createNamedQuery("Producto.consultaDePrecio", BigDecimal.class).setParameter("nombre", nombre).getSingleResult();
return em.createQuery(jpql, BigDecimal.class).setParameter("nombre", nombre).getSingleResult();
} }
} }

View File

@ -10,10 +10,12 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table; import javax.persistence.Table;
@Entity @Entity
@Table(name="productos") @Table(name="productos")
@NamedQuery(name="Producto.consultaDePrecio", query="SELECT P.precio FROM Producto AS P WHERE P.nombre=:nombre")
public class Producto { public class Producto {
@Id @Id

View File

@ -1,6 +1,7 @@
package com.latam.alura.tienda.prueba; package com.latam.alura.tienda.prueba;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.List;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
//import javax.persistence.EntityManagerFactory; //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.Pedido;
import com.latam.alura.tienda.modelo.Producto; import com.latam.alura.tienda.modelo.Producto;
import com.latam.alura.tienda.utils.JPAUtils; import com.latam.alura.tienda.utils.JPAUtils;
import com.latam.alura.tienda.vo.ReporteDeVenta;
public class RegistroDePedido { public class RegistroDePedido {
@ -39,6 +41,19 @@ public class RegistroDePedido {
pedidoDao.guardar(pedido); pedidoDao.guardar(pedido);
em.getTransaction().commit(); 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<Object[]> reporte = pedidoDao.ReporteVentas();
for (Object[] objects : reporte) {
System.out.print(objects[0] +", ");
System.out.print(objects[1] +", ");
System.out.println(objects[2]);
}
List<ReporteDeVenta> reporteVo = pedidoDao.ReporteVentasVO();
reporteVo.forEach(System.out::println);
} }
public static void RegistrarPedido() { public static void RegistrarPedido() {

View File

@ -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 : "") + "]";
}
}

View File

@ -2,7 +2,8 @@
<style>div.mermaid{text-align: center;}</style> <style>div.mermaid{text-align: center;}</style>
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 ```mermaid
erDiagram erDiagram
@ -18,7 +19,7 @@ erDiagram
id biging PK id biging PK
nombre string nombre string
} }
Clientes ||--o{ Pedidos : tiene Clientes ||--|{ Pedidos : tiene
Clientes { Clientes {
id bigint PK id bigint PK
nombre string nombre string
@ -81,7 +82,39 @@ creada anteriormente
- Mapeo de nuevas entidades en la aplicación según el modelado de la base de - Mapeo de nuevas entidades en la aplicación según el modelado de la base de
datos datos
- Mapeo de una relación con cardinalidad de muchos a muchos - Mapeo de relación con cardinalidad de muchos a muchos
- Mapeo de una relación bidireccional - Mapeo de relación bidireccional
- Persitencia entidades que tienen relaciones bidireccionales - 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 |
<br>
**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**