TP6.1 - Advanced Naming Conventions
Objectives
By the end of this practical work, you will be able to:
- ✅ Use the 15+ Spring Data JPA keywords
- ✅ Create complex queries without SQL
- ✅ Combine multiple keywords
- ✅ Test all your methods
Estimated duration: 2h
Prerequisites
- ✅ Chapter 1 of Module 6 completed
- ✅ Maven 3.9+ and Java 17+
- ✅ VS Code with Java extensions
Preparation: Create the Project
Step 1: Spring Initializr
Go to https://start.spring.io/
Configuration:
- Project: Maven
- Spring Boot: 3.2.0
- Group:
com.example - Artifact:
jpa-conventions - Packaging: Jar
- Java: 17
Dependencies:
- Spring Web
- Spring Data JPA
- H2 Database
Download, unzip, open in VS Code
Step 2: Configuration
File: 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
Exercise 1: Create the Product Entity
Step 1.1: Create the Entity
File: 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;
// Constructors
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 and Setters (all!)
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; }
}
Exercise 2: Create the Repository with 20 Methods
Step 2.1: Basic Repository
File: 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> {
// EASY LEVEL (5 methods)
// 1. Find by exact name
List<Product> findByName(String name);
// 2. Find by category
List<Product> findByCategory(String category);
// 3. Find active products
List<Product> findByActiveTrue();
// 4. Find inactive products
List<Product> findByActiveFalse();
// 5. Find by exact price
List<Product> findByPrice(Double price);
// MEDIUM LEVEL (10 methods)
// 6. Price less than
List<Product> findByPriceLessThan(Double maxPrice);
// 7. Price greater than
List<Product> findByPriceGreaterThan(Double minPrice);
// 8. Price in a range
List<Product> findByPriceBetween(Double min, Double max);
// 9. Stock less than (out of stock)
List<Product> findByStockLessThan(Integer minStock);
// 10. Name containing a keyword
List<Product> findByNameContaining(String keyword);
// 11. Name starting with
List<Product> findByNameStartingWith(String prefix);
// 12. Category in a list
List<Product> findByCategoryIn(List<String> categories);
// 13. Products without discount
List<Product> findByDiscountIsNull();
// 14. Products with discount
List<Product> findByDiscountIsNotNull();
// 15. Name case insensitive
List<Product> findByNameIgnoreCase(String name);
// ADVANCED LEVEL (5 methods)
// 16. Combination: Active AND price < max
List<Product> findByActiveTrueAndPriceLessThan(Double maxPrice);
// 17. Combination: Category AND stock > min, sorted by price
List<Product> findByCategoryAndStockGreaterThanOrderByPriceAsc(
String category,
Integer minStock
);
// 18. Combination: Active AND price in range AND category, sorted
List<Product> findByActiveTrueAndPriceBetweenAndCategoryOrderByNameAsc(
Double min,
Double max,
String category
);
// 19. Combination: Name containing OR category equal
List<Product> findByNameContainingOrCategory(String keyword, String category);
// 20. Created after a date, sorted by date
List<Product> findByCreatedAtAfterOrderByCreatedAtDesc(LocalDate date);
}
Exercise 3: Initialize Test Data
Step 3.1: Create DataLoader
File: 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("=== Initializing data ===");
// 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));
// Products with discount
Product macMini = new Product("Mac Mini", 699.99, 5, "Computers", true);
macMini.setDiscount(50.0);
repository.save(macMini);
// Inactive products
repository.save(new Product("Old Phone", 199.99, 0, "Phones", false));
// Out of stock products
repository.save(new Product("Rare Item", 1499.99, 2, "Electronics", true));
System.out.println("=== " + repository.count() + " products created ===");
};
}
}
Exercise 4: Create the Test Controller
Step 4.1: Complete Controller
File: 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: Complex combination
@GetMapping("/complex")
public List<Product> complex(
@RequestParam Double min,
@RequestParam Double max,
@RequestParam String category
) {
return productRepo.findByActiveTrueAndPriceBetweenAndCategoryOrderByNameAsc(
min, max, category
);
}
}
Exercise 5: Manual Tests
Start the Application
mvn clean install -DskipTests spring-boot:run
Console should display:
=== Initializing data ===
=== 10 products created ===
Test 1: Products by category
GET http://localhost:8080/api/products/by-category/Electronics
Expected result: 3 products (MacBook Pro, iPhone 15, iPad Pro, Rare Item)
Test 2: Active products
GET http://localhost:8080/api/products/active
Expected result: 9 products (all except "Old Phone")
Test 3: Products less than €700
GET http://localhost:8080/api/products/cheap/700
Expected result: Samsung Phone, Google Pixel, Mac Mini, Old Phone, HP Desktop
Test 4: Price between €600 and €1000
GET http://localhost:8080/api/products/price-range?min=600&max=1000
Expected result: Samsung Phone, Mac Mini, Dell Laptop, HP Desktop, iPhone 15
Test 5: Search by keyword
GET http://localhost:8080/api/products/search/Phone
Expected result: iPhone 15, Samsung Phone, Google Pixel, Old Phone
Test 6: Starts with "Mac"
GET http://localhost:8080/api/products/starts-with/Mac
Expected result: MacBook Pro, Mac Mini
Test 7: Multiple categories
GET http://localhost:8080/api/products/categories?categories=Electronics,Phones
Expected result: All Electronics + Phones products
Test 8: Products with discount
GET http://localhost:8080/api/products/with-discount
Expected result: Mac Mini (only one with discount)
Test 9: Active products less than €1000
GET http://localhost:8080/api/products/active-cheap/1000
Expected result: All active < €1000
Test 10: Complex search
GET http://localhost:8080/api/products/complex?min=500&max=1500&category=Electronics
Expected result: iPhone 15, iPad Pro, Rare Item (sorted by name)
Exercise 6: Unit Tests (Bonus)
Create the Tests
File: 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());
}
}
Run the tests:
mvn test
Challenge: Create 10 Additional Methods
Your turn! Create these methods:
- Find by description containing a keyword
- Find products created before a date
- Find by category AND active, sorted by price DESC
- Find products with stock between min and max
- Find by name ending with a suffix
- Find products with price >= min OR stock < min
- Find by category not in a list
- Find active products without discount
- Find by price AND sorted by stock DESC then name ASC
- Find the 5 cheapest products (hint: use Pageable)
Summary
What You Practiced
✅ 20 methods with naming conventions
✅ 9 different keywords (Between, LessThan, Containing, In, IsNull, True, False, IgnoreCase, OrderBy)
✅ Combinations of multiple keywords
✅ Manual tests with the browser
✅ Unit tests with JUnit
Next Step
You master the conventions! Move on to Entity Relationships (TP2).