Saltar al contenido principal

TP6.1 - Convenciones de Nomenclatura Avanzadas

Objetivos​

Al final de este TP, usted será capaz de:

  1. ✅ Utilizar las 15+ palabras clave de Spring Data JPA
  2. ✅ Crear consultas complejas sin SQL
  3. ✅ Combinar varias palabras clave
  4. ✅ Probar todos sus métodos

Duración estimada: 2h


Requisitos Previos​

  • ✅ Capítulo 1 del Módulo 6 completado
  • ✅ Maven 3.9+ y Java 17+
  • ✅ VS Code con extensiones de Java

Preparación: Crear el Proyecto​

Paso 1: Spring Initializr​

Vaya a https://start.spring.io/

Configuración:

  • Project: Maven
  • Spring Boot: 3.2.0
  • Group: com.example
  • Artifact: jpa-conventions
  • Packaging: Jar
  • Java: 17

Dependencias:

  • Spring Web
  • Spring Data JPA
  • H2 Database

Descargue, descomprima, abra en VS Code


Paso 2: Configuración​

Archivo: src/main/resources/application.properties

# H2 Database
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# H2 Console
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

# JPA
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

# Server
server.port=8080

Ejercicio 1: Crear la Entidad Product​

Paso 1.1: Crear la Entidad​

Archivo: model/Product.java

package com.example.jpa.model;

import jakarta.persistence.*;
import java.time.LocalDate;

@Entity
@Table(name = "products")
public class Product {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;
private String description;
private Double price;
private Integer stock;
private String category;
private Boolean active;
private Double discount;
private LocalDate createdAt;

// Constructeurs
public Product() {}

public Product(String name, Double price, Integer stock, String category, Boolean active) {
this.name = name;
this.price = price;
this.stock = stock;
this.category = category;
this.active = active;
this.createdAt = LocalDate.now();
}

// Getters et Setters (tous!)
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }

public String getName() { return name; }
public void setName(String name) { this.name = name; }

public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }

public Double getPrice() { return price; }
public void setPrice(Double price) { this.price = price; }

public Integer getStock() { return stock; }
public void setStock(Integer stock) { this.stock = stock; }

public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }

public Boolean getActive() { return active; }
public void setActive(Boolean active) { this.active = active; }

public Double getDiscount() { return discount; }
public void setDiscount(Double discount) { this.discount = discount; }

public LocalDate getCreatedAt() { return createdAt; }
public void setCreatedAt(LocalDate createdAt) { this.createdAt = createdAt; }
}

Ejercicio 2: Crear el Repository con 20 Métodos​

Paso 2.1: Repository Básico​

Archivo: repository/ProductRepository.java

package com.example.jpa.repository;

import com.example.jpa.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.util.List;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {

// NIVEL FÁCIL (5 métodos)

// 1. Buscar por nombre exacto
List<Product> findByName(String name);

// 2. Buscar por categoría
List<Product> findByCategory(String category);

// 3. Buscar productos activos
List<Product> findByActiveTrue();

// 4. Buscar productos inactivos
List<Product> findByActiveFalse();

// 5. Buscar por precio exacto
List<Product> findByPrice(Double price);


// NIVEL MEDIO (10 métodos)

// 6. Precio menor que
List<Product> findByPriceLessThan(Double maxPrice);

// 7. Precio mayor que
List<Product> findByPriceGreaterThan(Double minPrice);

// 8. Precio en un intervalo
List<Product> findByPriceBetween(Double min, Double max);

// 9. Stock menor que (agotado)
List<Product> findByStockLessThan(Integer minStock);

// 10. Nombre que contiene una palabra clave
List<Product> findByNameContaining(String keyword);

// 11. Nombre que empieza por
List<Product> findByNameStartingWith(String prefix);

// 12. Categoría en una lista
List<Product> findByCategoryIn(List<String> categories);

// 13. Productos sin descuento
List<Product> findByDiscountIsNull();

// 14. Productos con descuento
List<Product> findByDiscountIsNotNull();

// 15. Nombre insensible a mayúsculas/minúsculas
List<Product> findByNameIgnoreCase(String name);


// NIVEL AVANZADO (5 métodos)

// 16. Combinación: Activo Y precio < max
List<Product> findByActiveTrueAndPriceLessThan(Double maxPrice);

// 17. Combinación: Categoría Y stock > min, ordenados por precio
List<Product> findByCategoryAndStockGreaterThanOrderByPriceAsc(
String category,
Integer minStock
);

// 18. Combinación: Activo Y precio en intervalo Y categoría, ordenados
List<Product> findByActiveTrueAndPriceBetweenAndCategoryOrderByNameAsc(
Double min,
Double max,
String category
);

// 19. Combinación: Nombre contiene O categoría igual
List<Product> findByNameContainingOrCategory(String keyword, String category);

// 20. Creados después de una fecha, ordenados por fecha
List<Product> findByCreatedAtAfterOrderByCreatedAtDesc(LocalDate date);
}

Ejercicio 3: Inicializar los Datos de Prueba​

Paso 3.1: Crear DataLoader​

Archivo: config/DataLoader.java

package com.example.jpa.config;

import com.example.jpa.model.Product;
import com.example.jpa.repository.ProductRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;

@Configuration
public class DataLoader {

@Bean
CommandLineRunner initDatabase(ProductRepository repository) {
return args -> {
System.out.println("=== Inicialización de datos ===");

// Electronics
repository.save(new Product("MacBook Pro", 2499.99, 15, "Electronics", true));
repository.save(new Product("iPhone 15", 999.99, 50, "Electronics", true));
repository.save(new Product("iPad Pro", 1299.99, 30, "Electronics", true));

// Computers
repository.save(new Product("Dell Laptop", 899.99, 25, "Computers", true));
repository.save(new Product("HP Desktop", 799.99, 10, "Computers", true));

// Phones
repository.save(new Product("Samsung Phone", 699.99, 40, "Phones", true));
repository.save(new Product("Google Pixel", 599.99, 20, "Phones", true));

// Productos con descuento
Product macMini = new Product("Mac Mini", 699.99, 5, "Computers", true);
macMini.setDiscount(50.0);
repository.save(macMini);

// Productos inactivos
repository.save(new Product("Old Phone", 199.99, 0, "Phones", false));

// Productos agotados
repository.save(new Product("Rare Item", 1499.99, 2, "Electronics", true));

System.out.println("=== " + repository.count() + " productos creados ===");
};
}
}

Ejercicio 4: Crear el Controller de Prueba​

Paso 4.1: Controller Completo​

Archivo: controller/ProductController.java

package com.example.jpa.controller;

import com.example.jpa.model.Product;
import com.example.jpa.repository.ProductRepository;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

private final ProductRepository productRepo;

public ProductController(ProductRepository productRepo) {
this.productRepo = productRepo;
}

// Test 1: findByName
@GetMapping("/by-name/{name}")
public List<Product> byName(@PathVariable String name) {
return productRepo.findByName(name);
}

// Test 2: findByCategory
@GetMapping("/by-category/{category}")
public List<Product> byCategory(@PathVariable String category) {
return productRepo.findByCategory(category);
}

// Test 3: findByActiveTrue
@GetMapping("/active")
public List<Product> activeProducts() {
return productRepo.findByActiveTrue();
}

// Test 4: findByActiveFalse
@GetMapping("/inactive")
public List<Product> inactiveProducts() {
return productRepo.findByActiveFalse();
}

// Test 5: findByPriceLessThan
@GetMapping("/cheap/{maxPrice}")
public List<Product> cheapProducts(@PathVariable Double maxPrice) {
return productRepo.findByPriceLessThan(maxPrice);
}

// Test 6: findByPriceGreaterThan
@GetMapping("/expensive/{minPrice}")
public List<Product> expensiveProducts(@PathVariable Double minPrice) {
return productRepo.findByPriceGreaterThan(minPrice);
}

// Test 7: findByPriceBetween
@GetMapping("/price-range")
public List<Product> priceRange(
@RequestParam Double min,
@RequestParam Double max
) {
return productRepo.findByPriceBetween(min, max);
}

// Test 8: findByStockLessThan
@GetMapping("/low-stock/{minStock}")
public List<Product> lowStock(@PathVariable Integer minStock) {
return productRepo.findByStockLessThan(minStock);
}

// Test 9: findByNameContaining
@GetMapping("/search/{keyword}")
public List<Product> search(@PathVariable String keyword) {
return productRepo.findByNameContaining(keyword);
}

// Test 10: findByNameStartingWith
@GetMapping("/starts-with/{prefix}")
public List<Product> startsWith(@PathVariable String prefix) {
return productRepo.findByNameStartingWith(prefix);
}

// Test 11: findByCategoryIn
@GetMapping("/categories")
public List<Product> byCategories(@RequestParam List<String> categories) {
return productRepo.findByCategoryIn(categories);
}

// Test 12: findByDiscountIsNull
@GetMapping("/no-discount")
public List<Product> noDiscount() {
return productRepo.findByDiscountIsNull();
}

// Test 13: findByDiscountIsNotNull
@GetMapping("/with-discount")
public List<Product> withDiscount() {
return productRepo.findByDiscountIsNotNull();
}

// Test 14: findByActiveTrueAndPriceLessThan
@GetMapping("/active-cheap/{maxPrice}")
public List<Product> activeCheap(@PathVariable Double maxPrice) {
return productRepo.findByActiveTrueAndPriceLessThan(maxPrice);
}

// Test 15: Combinación compleja
@GetMapping("/complex")
public List<Product> complex(
@RequestParam Double min,
@RequestParam Double max,
@RequestParam String category
) {
return productRepo.findByActiveTrueAndPriceBetweenAndCategoryOrderByNameAsc(
min, max, category
);
}
}

Ejercicio 5: Pruebas Manuales​

Iniciar la Aplicación​

mvn clean install -DskipTests spring-boot:run

La consola debería mostrar:

=== Inicialización de datos ===
=== 10 productos creados ===

Prueba 1: Productos por categoría​

GET http://localhost:8080/api/products/by-category/Electronics

Resultado esperado: 3 productos (MacBook Pro, iPhone 15, iPad Pro, Rare Item)


Prueba 2: Productos activos​

GET http://localhost:8080/api/products/active

Resultado esperado: 9 productos (todos excepto "Old Phone")


Prueba 3: Productos menos de 700€​

GET http://localhost:8080/api/products/cheap/700

Resultado esperado: Samsung Phone, Google Pixel, Mac Mini, Old Phone, HP Desktop


Prueba 4: Precio entre 600€ y 1000€​

GET http://localhost:8080/api/products/price-range?min=600&max=1000

Resultado esperado: Samsung Phone, Mac Mini, Dell Laptop, HP Desktop, iPhone 15


Prueba 5: Búsqueda por palabra clave​

GET http://localhost:8080/api/products/search/Phone

Resultado esperado: iPhone 15, Samsung Phone, Google Pixel, Old Phone


Prueba 6: Empieza por "Mac"​

GET http://localhost:8080/api/products/starts-with/Mac

Resultado esperado: MacBook Pro, Mac Mini


Prueba 7: Varias categorías​

GET http://localhost:8080/api/products/categories?categories=Electronics,Phones

Resultado esperado: Todos los productos Electronics + Phones


Prueba 8: Productos con descuento​

GET http://localhost:8080/api/products/with-discount

Resultado esperado: Mac Mini (único con discount)


Prueba 9: Productos activos menos de 1000€​

GET http://localhost:8080/api/products/active-cheap/1000

Resultado esperado: Todos los activos < 1000€


Prueba 10: Búsqueda compleja​

GET http://localhost:8080/api/products/complex?min=500&max=1500&category=Electronics

Resultado esperado: iPhone 15, iPad Pro, Rare Item (ordenados por nombre)


Ejercicio 6: Pruebas Unitarias (Bonus)​

Crear las Pruebas​

Archivo: src/test/java/ProductRepositoryTest.java

package com.example.jpa;

import com.example.jpa.model.Product;
import com.example.jpa.repository.ProductRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import java.util.Arrays;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

@DataJpaTest
public class ProductRepositoryTest {

@Autowired
private ProductRepository productRepo;

@BeforeEach
void setUp() {
productRepo.deleteAll();

productRepo.save(new Product("Laptop", 999.99, 10, "Computers", true));
productRepo.save(new Product("Phone", 599.99, 20, "Phones", true));
productRepo.save(new Product("Tablet", 399.99, 5, "Electronics", false));
}

@Test
void testFindByPriceLessThan() {
List<Product> results = productRepo.findByPriceLessThan(700.0);
assertEquals(2, results.size());
}

@Test
void testFindByActiveTrue() {
List<Product> results = productRepo.findByActiveTrue();
assertEquals(2, results.size());
}

@Test
void testFindByNameContaining() {
List<Product> results = productRepo.findByNameContaining("top");
assertEquals(1, results.size());
assertEquals("Laptop", results.get(0).getName());
}

@Test
void testFindByCategoryIn() {
List<String> categories = Arrays.asList("Computers", "Phones");
List<Product> results = productRepo.findByCategoryIn(categories);
assertEquals(2, results.size());
}

@Test
void testFindByPriceBetween() {
List<Product> results = productRepo.findByPriceBetween(400.0, 1000.0);
assertEquals(2, results.size());
}
}

Ejecutar las pruebas:

mvn test

Challenge: Cree 10 Métodos Adicionales​

¡Le toca a usted! Cree estos métodos:

  1. Buscar por descripción que contenga una palabra clave
  2. Buscar productos creados antes de una fecha
  3. Buscar por categoría Y activo, ordenados por precio DESC
  4. Buscar productos con stock entre min y max
  5. Buscar por nombre que termine con un sufijo
  6. Buscar productos con precio >= min O stock < min
  7. Buscar por categoría que no esté en una lista
  8. Buscar productos activos sin descuento
  9. Buscar por precio Y ordenados por stock DESC y luego nombre ASC
  10. Buscar los 5 productos más baratos (hint: use Pageable)

Resumen​

Lo que Ha Practicado​

✅ 20 métodos con las convenciones de nomenclatura
✅ 9 palabras clave diferentes (Between, LessThan, Containing, In, IsNull, True, False, IgnoreCase, OrderBy)
✅ Combinaciones de varias palabras clave
✅ Pruebas manuales con el navegador
✅ Pruebas unitarias con JUnit


Próximo Paso​

¡Usted domina las convenciones! Pase a las Relaciones entre Entidades (TP2).

➡️ TP6.2: Relaciones Employee-Department

⬅️ Volver al Módulo 6