diff --git a/.gitignore b/.gitignore index 7cb8db5..57a9e2a 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ bin/ *.uxf *.umlcd target/ +*.trace.db diff --git a/010_spring_boot/README.md b/010_spring_boot/README.md index b7b499a..b9f2c3b 100644 --- a/010_spring_boot/README.md +++ b/010_spring_boot/README.md @@ -9,3 +9,6 @@ Java y [bases de datos](./base_de_datos.md) 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 diff --git a/010_spring_boot/jpa/tienda2/database/tienda.mv.db b/010_spring_boot/jpa/tienda2/database/tienda.mv.db new file mode 100644 index 0000000..a46f057 Binary files /dev/null and b/010_spring_boot/jpa/tienda2/database/tienda.mv.db differ diff --git a/010_spring_boot/jpa/tienda2/pom.xml b/010_spring_boot/jpa/tienda2/pom.xml new file mode 100644 index 0000000..17a84e2 --- /dev/null +++ b/010_spring_boot/jpa/tienda2/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + com.latam.alura.tienda + tienda + 0.0.1-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + ${java.version} + ${java.version} + true + UTF-8 + ${java.version} + true + /usr/bin/java + + + + + + + org.hibernate + hibernate-entitymanager + 5.6.15.Final + + + com.h2database + h2 + 2.2.222 + runtime + + + + 17 + ${java.version} + ${java.version} + UTF-8 + + \ No newline at end of file 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 new file mode 100644 index 0000000..369514b --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/CategoriaDao.java @@ -0,0 +1,38 @@ +package com.latam.alura.tienda.dao; + +import java.util.List; + +import javax.persistence.EntityManager; + +import com.latam.alura.tienda.modelo.Categoria; + +public class CategoriaDao { + + private EntityManager em; + + public CategoriaDao(EntityManager em) { + this.em = em; + } + + public void guardar(Categoria categoria) { + this.em.persist(categoria); + } + + public void actualizar(Categoria categoria) { + this.em.merge(categoria); + } + + public void remover(Categoria categoria) { + categoria = this.em.merge(categoria); + this.em.remove(categoria); + } + + public Categoria consultaPorId(Long id) { + return em.find(Categoria.class, id); + } + + public List consultarTodos() { + 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/ClienteDao.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/ClienteDao.java new file mode 100644 index 0000000..644de8f --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/ClienteDao.java @@ -0,0 +1,54 @@ +package com.latam.alura.tienda.dao; + +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.EntityManager; + +import com.latam.alura.tienda.modelo.Cliente; + +public class ClienteDao { + + private EntityManager em; + + public ClienteDao(EntityManager em) { + this.em = em; + } + + public void guardar(Cliente cliente) { + this.em.persist(cliente); + } + + public void actualizar(Cliente cliente) { + this.em.merge(cliente); + } + + public void remover(Cliente cliente) { + cliente = this.em.merge(cliente); + this.em.remove(cliente); + } + + public Cliente consultaPorId(Long id) { + return em.find(Cliente.class, id); + } + + public List consultarTodos() { + String jpql = "SELECT P FROM Cliente AS P"; + return em.createQuery(jpql, Cliente.class).getResultList(); + } + + public List consultaPorNombre(String nombre) { + String jpql = "SELECT P FROM Cliente AS P WHERE P.nombre=:nombre"; + return em.createQuery(jpql, Cliente.class).setParameter("nombre", nombre).getResultList(); + } + + public List consultaPorNombreDeCategoria(String nombre) { + String jpql = "SELECT P FROM Cliente AS P WHERE P.categoria.nombre=:nombre"; + return em.createQuery(jpql, Cliente.class).setParameter("nombre", nombre).getResultList(); + } + + public BigDecimal consultaPrecioPorNombreDeCliente(String nombre) { + String jpql = "SELECT P.precio FROM Cliente AS P WHERE P.nombre=:nombre"; + return em.createQuery(jpql, BigDecimal.class).setParameter("nombre", nombre).getSingleResult(); + } +} 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 new file mode 100644 index 0000000..6504ddf --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/PedidoDao.java @@ -0,0 +1,54 @@ +package com.latam.alura.tienda.dao; + +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.EntityManager; + +import com.latam.alura.tienda.modelo.Pedido; + +public class PedidoDao { + + private EntityManager em; + + public PedidoDao(EntityManager em) { + this.em = em; + } + + public void guardar(Pedido pedido) { + this.em.persist(pedido); + } + + public void actualizar(Pedido pedido) { + this.em.merge(pedido); + } + + public void remover(Pedido pedido) { + pedido = this.em.merge(pedido); + this.em.remove(pedido); + } + + public Pedido consultaPorId(Long id) { + return em.find(Pedido.class, id); + } + + public List consultarTodos() { + String jpql = "SELECT P FROM Pedido AS P"; + return em.createQuery(jpql, Pedido.class).getResultList(); + } + + public List consultaPorNombre(String nombre) { + String jpql = "SELECT P FROM Pedido AS P WHERE P.nombre=:nombre"; + return em.createQuery(jpql, Pedido.class).setParameter("nombre", nombre).getResultList(); + } + + public List consultaPorNombreDeCategoria(String nombre) { + String jpql = "SELECT P FROM Pedido AS P WHERE P.categoria.nombre=:nombre"; + return em.createQuery(jpql, Pedido.class).setParameter("nombre", nombre).getResultList(); + } + + public BigDecimal consultaPrecioPorNombreDePedido(String nombre) { + String jpql = "SELECT P.precio FROM Pedido AS P WHERE P.nombre=:nombre"; + return em.createQuery(jpql, BigDecimal.class).setParameter("nombre", nombre).getSingleResult(); + } +} 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 new file mode 100644 index 0000000..4688d56 --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/dao/ProductoDao.java @@ -0,0 +1,54 @@ +package com.latam.alura.tienda.dao; + +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.EntityManager; + +import com.latam.alura.tienda.modelo.Producto; + +public class ProductoDao { + + private EntityManager em; + + public ProductoDao(EntityManager em) { + this.em = em; + } + + public void guardar(Producto producto) { + this.em.persist(producto); + } + + public void actualizar(Producto producto) { + this.em.merge(producto); + } + + public void remover(Producto producto) { + producto = this.em.merge(producto); + this.em.remove(producto); + } + + public Producto consultaPorId(Long id) { + return em.find(Producto.class, id); + } + + public List consultarTodos() { + String jpql = "SELECT P FROM Producto AS P"; + return em.createQuery(jpql, Producto.class).getResultList(); + } + + public List consultaPorNombre(String nombre) { + String jpql = "SELECT P FROM Producto AS P WHERE P.nombre=:nombre"; + return em.createQuery(jpql, Producto.class).setParameter("nombre", nombre).getResultList(); + } + + public List consultaPorNombreDeCategoria(String nombre) { + String jpql = "SELECT P FROM Producto AS P WHERE P.categoria.nombre=:nombre"; + return em.createQuery(jpql, Producto.class).setParameter("nombre", nombre).getResultList(); + } + + 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(); + } +} diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Categoria.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Categoria.java new file mode 100644 index 0000000..ca3d679 --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Categoria.java @@ -0,0 +1,46 @@ +package com.latam.alura.tienda.modelo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +//public enum Categoria { +// SOFTWARES, +// LIBROS, +// CELULARES +//} + +@Entity +@Table(name="categorias") +public class Categoria { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String nombre; + + public Categoria() {} + + public Categoria(String nombre) { + this.nombre = nombre; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + +} \ No newline at end of file diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Cliente.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Cliente.java new file mode 100644 index 0000000..29dded1 --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Cliente.java @@ -0,0 +1,51 @@ +package com.latam.alura.tienda.modelo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + + +@Entity +@Table(name="clientes") +public class Cliente { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String nombre; + private String dni; + + public Cliente() {} + + public Cliente(String nombre, String dni) { + this.nombre = nombre; + this.dni = dni; + } + + public Cliente(String nombre) { + this.nombre = nombre; + } + + public Long getId() { + return id; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getDni() { + return dni; + } + + public void setDni(String dni) { + this.dni = dni; + } + +} \ No newline at end of file diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/ItemsPedido.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/ItemsPedido.java new file mode 100644 index 0000000..594eac1 --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/ItemsPedido.java @@ -0,0 +1,74 @@ +package com.latam.alura.tienda.modelo; + +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name="items_pedido") +public class ItemsPedido { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + private Long id; + private Integer cantidad; + private BigDecimal precio_unitario; + @ManyToOne + private Producto producto; + @ManyToOne + private Pedido pedido; + + public ItemsPedido() {} + + public ItemsPedido(Integer cantidad, Producto producto, Pedido pedido) { + this.producto = producto; + this.cantidad = cantidad; + this.pedido = pedido; + this.precio_unitario = producto.getPrecio(); + } + + public Integer getCantidad() { + return cantidad; + } + + public void setCantidad(Integer cantidad) { + this.cantidad = cantidad; + } + + public BigDecimal getPrecio_unitario() { + return precio_unitario; + } + + public void setPrecio_unitario(BigDecimal precio_unitario) { + this.precio_unitario = precio_unitario; + } + + public Producto getProducto() { + return producto; + } + + public void setProducto(Producto producto) { + this.producto = producto; + } + + public Pedido getPedido() { + return pedido; + } + + public void setPedido(Pedido pedido) { + this.pedido = pedido; + } + + public Long getId() { + return id; + } + + public BigDecimal getValor() { + return this.precio_unitario.multiply(new BigDecimal(this.cantidad)); + } + +} diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Pedido.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Pedido.java new file mode 100644 index 0000000..0624156 --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Pedido.java @@ -0,0 +1,76 @@ +package com.latam.alura.tienda.modelo; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +//import javax.persistence.JoinTable; +//import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; + + +@Entity +@Table(name="pedidos") +public class Pedido { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private LocalDate fecha = LocalDate.now(); + private BigDecimal valorTotal = new BigDecimal(0); + @ManyToOne + private Cliente cliente; + //@ManyToMany + //@JoinTable(name="item_pedido") + @OneToMany(mappedBy = "pedido", cascade = CascadeType.ALL) + private List items = new ArrayList<>(); + + public Pedido() {} + + public Pedido(Cliente cliente) { + this.cliente = cliente; + } + + public void agregarItems(ItemsPedido item) { + item.setPedido(this); + this.items.add(item); + this.valorTotal = this.valorTotal.add(item.getValor()); + } + + public Long getId() { + return id; + } + + public LocalDate getFecha() { + return fecha; + } + + public void setFecha(LocalDate fecha) { + this.fecha = fecha; + } + + public BigDecimal getValorTotal() { + return valorTotal; + } + + public void setValorTotal(BigDecimal valorTotal) { + this.valorTotal = valorTotal; + } + + public Cliente getCliente() { + return cliente; + } + + public void setCliente(Cliente cliente) { + this.cliente = cliente; + } + +} \ No newline at end of file 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 new file mode 100644 index 0000000..0db6112 --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/modelo/Producto.java @@ -0,0 +1,75 @@ +package com.latam.alura.tienda.modelo; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import javax.persistence.Entity; +//import javax.persistence.EnumType; +//import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name="productos") +public class Producto { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + private Long id; + // @Column(name="nombres") + private String nombre; + private String descripcion; + private BigDecimal precio; + private LocalDate fechaDeRegistro = LocalDate.now(); + //@Enumerated(EnumType.STRING) + @ManyToOne + private Categoria categoria; + + public Producto() {} + + public Producto(String nombre, String descripcion, BigDecimal precio, Categoria categoria) { + this.nombre = nombre; + this.descripcion = descripcion; + this.precio = precio; + this.categoria = categoria; + } + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getDescripcion() { + return descripcion; + } + + public void setDescripcion(String descripcion) { + this.descripcion = descripcion; + } + + public BigDecimal getPrecio() { + return precio; + } + + public void setPrecio(BigDecimal precio) { + this.precio = precio; + } + + public LocalDate getFechaDeRegistro() { + return fechaDeRegistro; + } + +} 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 new file mode 100644 index 0000000..e596c32 --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/prueba/RegistroDePedido.java @@ -0,0 +1,58 @@ +package com.latam.alura.tienda.prueba; + +import java.math.BigDecimal; + +import javax.persistence.EntityManager; +//import javax.persistence.EntityManagerFactory; +//import javax.persistence.Persistence; + +import com.latam.alura.tienda.dao.CategoriaDao; +import com.latam.alura.tienda.dao.ClienteDao; +import com.latam.alura.tienda.dao.PedidoDao; +import com.latam.alura.tienda.dao.ProductoDao; +import com.latam.alura.tienda.modelo.Categoria; +import com.latam.alura.tienda.modelo.Cliente; +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; + +public class RegistroDePedido { + + public static void main(String[] args) { + RegistrarPedido(); + + EntityManager em = JPAUtils.getEntityManager(); + + ProductoDao productoDao = new ProductoDao(em); + Producto producto = productoDao.consultaPorId(1L); + + ClienteDao clienteDao = new ClienteDao(em); + Cliente cliente = new Cliente("Juan","mnwenic"); + + PedidoDao pedidoDao = new PedidoDao(em); + Pedido pedido = new Pedido(cliente); + pedido.agregarItems(new ItemsPedido(5,producto, pedido)); + + em.getTransaction().begin(); + clienteDao.guardar(cliente); + + pedidoDao.guardar(pedido); + em.getTransaction().commit(); + } + + public static void RegistrarPedido() { + Categoria celulares = new Categoria("Celulares"); + Producto celular = new Producto("Samsung", "Teléfono usado", new BigDecimal("1000"), celulares); + EntityManager em = JPAUtils.getEntityManager(); + ProductoDao productoDao = new ProductoDao(em); + CategoriaDao categoriaDao = new CategoriaDao(em); + + em.getTransaction().begin(); + categoriaDao.guardar(celulares); + productoDao.guardar(celular); + em.getTransaction().commit(); + em.close(); + } + +} diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/prueba/RegistroDeProducto.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/prueba/RegistroDeProducto.java new file mode 100644 index 0000000..0805acd --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/prueba/RegistroDeProducto.java @@ -0,0 +1,121 @@ +package com.latam.alura.tienda.prueba; + +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.EntityManager; +//import javax.persistence.EntityManagerFactory; +//import javax.persistence.Persistence; + +import com.latam.alura.tienda.dao.CategoriaDao; +import com.latam.alura.tienda.dao.ProductoDao; +import com.latam.alura.tienda.modelo.Categoria; +import com.latam.alura.tienda.modelo.Producto; +import com.latam.alura.tienda.utils.JPAUtils; + +public class RegistroDeProducto { + + public static void main(String[] args) { + RegistrarProducto(); + EntityManager em = JPAUtils.getEntityManager(); + ProductoDao productoDao = new ProductoDao(em); + Producto producto = productoDao.consultaPorId(1L); + System.out.println(producto.getNombre()); + + List productos = productoDao.consultarTodos(); + productos.forEach(producto_ -> System.out.println(producto_.getDescripcion())); + + CategoriaDao categoriaDao = new CategoriaDao(em); + List categorias = categoriaDao.consultarTodos(); + categorias.forEach(categoria_ -> System.out.println(categoria_.getNombre())); + + List productos_por_nombre = productoDao.consultaPorNombre("Samsung"); + productos_por_nombre.forEach(producto_ -> System.out.println(producto_.getDescripcion())); + + List productos_por_nombre_categoria = productoDao.consultaPorNombreDeCategoria("Celulares"); + productos_por_nombre_categoria.forEach(producto_ -> System.out.println(producto_.getDescripcion())); + + BigDecimal precio_producto = productoDao.consultaPrecioPorNombreDeProducto("Samsung"); + System.out.println(precio_producto); + /* + Categoria celulares = new Categoria("Celulares"); + //Producto celular = new Producto("Samsung", "Teléfono usado", new BigDecimal("1000"), Categoria.CELULARES); + Producto celular = new Producto("Samsung", "Teléfono usado", new BigDecimal("1000"), celulares); + //celular.setNombre("Samsung"); + //celular.setDescripcion("Teléfono usado"); + //celular.setPrecio(new BigDecimal("1000")); + + //EntityManagerFactory factory = Persistence.createEntityManagerFactory("tienda"); + //EntityManager em = factory.createEntityManager(); + EntityManager em = JPAUtils.getEntityManager(); + + ProductoDao productoDao = new ProductoDao(em); + CategoriaDao categoriaDao = new CategoriaDao(em); + + em.getTransaction().begin(); + categoriaDao.guardar(celulares); + productoDao.guardar(celular); + //em.persist(celular); + //em.getTransaction().commit(); + em.flush(); + em.clear(); + //em.close(); + */ + + // Acciones por aula + //em.getTransaction().begin(); + + //V1 + /* + em.getTransaction().begin(); + em.persist(celulares); + celulares.setNombre("LAPTOPS"); + em.getTransaction().commit(); + em.close(); + celulares.setNombre("PANTALLAS"); + */ + + //V2 + /* + em.persist(celulares); + celulares.setNombre("LAPTOPS"); + em.flush(); + em.clear(); + + celulares = em.merge(celulares); + celulares.setNombre("PANTALLAS"); + em.flush(); + em.remove(celulares); + */ + + //V3 + /* + em.persist(celulares); + celulares.setNombre("LAPTOPS"); + em.flush(); + em.clear(); + + celulares = em.merge(celulares); + celulares.setNombre("PANTALLAS"); + em.flush(); + //em.clear(); + em.remove(celulares); + em.flush(); + */ + } + + public static void RegistrarProducto() { + Categoria celulares = new Categoria("Celulares"); + Producto celular = new Producto("Samsung", "Teléfono usado", new BigDecimal("1000"), celulares); + EntityManager em = JPAUtils.getEntityManager(); + ProductoDao productoDao = new ProductoDao(em); + CategoriaDao categoriaDao = new CategoriaDao(em); + + em.getTransaction().begin(); + categoriaDao.guardar(celulares); + productoDao.guardar(celular); + em.getTransaction().commit(); + em.close(); + } + +} diff --git a/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/utils/JPAUtils.java b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/utils/JPAUtils.java new file mode 100644 index 0000000..e9a394b --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/java/com/latam/alura/tienda/utils/JPAUtils.java @@ -0,0 +1,14 @@ +package com.latam.alura.tienda.utils; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +public class JPAUtils { + + private static EntityManagerFactory FACTORY = Persistence.createEntityManagerFactory("tienda"); + + public static EntityManager getEntityManager() { + return FACTORY.createEntityManager(); + } +} diff --git a/010_spring_boot/jpa/tienda2/src/main/resources/META-INF/persistence.xml b/010_spring_boot/jpa/tienda2/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000..86d7673 --- /dev/null +++ b/010_spring_boot/jpa/tienda2/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/010_spring_boot/jpa_avanzado.md b/010_spring_boot/jpa_avanzado.md new file mode 100644 index 0000000..752d78e --- /dev/null +++ b/010_spring_boot/jpa_avanzado.md @@ -0,0 +1,87 @@ +# JPA Avanzado + + + +Retomando el proyecto [anterior](./jpa/tienda/src/main/java/com/latam/alura/tienda/) + +```mermaid +erDiagram + Categorias ||--o{ Productos : tiene + Productos { + id bigint PK + nombre varchar + descripcion varchar + precio decimal + categoria_id bigint FK + } + Categorias { + id biging PK + nombre string + } + Clientes ||--o{ Pedidos : tiene + Clientes { + id bigint PK + nombre string + dni string + } + Pedidos { + id bigint PK + fecha date + valor_total decimal + cliente_id bigint FK + } + Items_Pedido { + id bigint PK + producto_id biging FK + pedido_id bigint FK + precio_unitario decimal + cantidad int + } + Pedidos ||--|{ Items_Pedido : tiene + Items_Pedido }|--|| Productos: tiene +``` + +## H2 + +Alias para manejar H2 + +```bash +alias h2server='java -cp ${HOME}/.m2/repository/com/h2database/h2/2.2.222/h2-2.2.222.jar org.h2.tools.Server -tcpAllowOthers -pgAllowOthers' +alias h2console='java -jar ${HOME}/.m2/repository/com/h2database/h2/2.2.222/h2-2.2.222.jar' +``` + +- Creación de base de datos `h2console` + +### H2 en modo servidor + +```bash +h2server + +TCP server running at tcp://127.0.1.1:9092 (others can connect) +PG server running at pg://127.0.1.1:5435 (others can connect) +Web Console server running at http://127.0.1.1:8082 (only local connections) +``` + + +En [pom.xml](./jpa/tienda2/pom.xml) cambiar la `url` para usar base de datos +creada anteriormente + +```xml +... + + ... + + ... + +... +``` + +#### Sumario Aula 1 + +- 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 + diff --git a/010_spring_boot/jpa_persistencia_hibernate.md b/010_spring_boot/jpa_persistencia_hibernate.md index d9d0fba..db43069 100644 --- a/010_spring_boot/jpa_persistencia_hibernate.md +++ b/010_spring_boot/jpa_persistencia_hibernate.md @@ -82,7 +82,7 @@ OJP-->JP end ``` -JPA es una capa (una abstarcción) se debe usar una biblioteca que la implemente +JPA es una capa (una abstracción) se debe usar una biblioteca que la implemente Existen detalles específicos de Hibernate que dificultan cambiar de implementacion de JPA. Es recomendable mantenerse dentro del patrón de JPA. @@ -169,10 +169,10 @@ erDiagram Productos }|--|| Categorias : tiene Productos { id bigint PK - Nombre varchar - Descripcion varchar - Precio decimal - categoria_id int FK + nombre varchar + descripcion varchar + precio decimal + categoria_id bigint FK } Categorias { id biging PK diff --git a/README.md b/README.md index 2784fe1..654f977 100644 --- a/README.md +++ b/README.md @@ -49,3 +49,4 @@ primoridiales en programación con Javascript - [Base de datos](./010_spring_boot/base_de_datos.md) - [JDBC](./010_spring_boot/jdbc.md) - [Persistencia con JPA - Hibernate](./010_spring_boot/jpa_persistencia_hibernate.md) + - [JPA consultas avanzadas, rendimiento y modelos complejos](./010_spring_boot/jpa_avanzado.md)