Project using SpringBoot, Data JPA and PostGreSQL
Available data in DataBase:
To fetch all the data from the database
public List<Product> getAllProducts(){
return db.findAll();
}
ProductService -
public static void getAllProducts(ProductService service){
System.out.println("Available data in Database");
List<Product> products = service.getAllProducts();
for(Product p : products){
System.out.println(p);
}
}
Assignment 1: Search by Product Name
public static void getProductByName(ProductService service){
List<Product> products = service.getProductByName("BlackBeast");
System.out.println("Data which is having name as BlackBeast in Database");
for(Product p : products){
System.out.println(p);
}
}
ProductService -
public List<Product> getProductByName(String name){
return db.findByNameIgnoreCase(name.toLowerCase());
}
I used the findByNameIgnoreCase() method which takes the String as an argument to fetch the list of products by name, Where I handled the case-sensitive scenario as well.
Output result:
Assignment 2: Search by Products by text
Recommended by LinkedIn
public static void getProductsByText(ProductService service){
List<Product> products = service.getProductsByText("laptop");
System.out.println("Data which is having laptop text in any column in Database");
for(Product p : products){
System.out.println(p);
}
}
ProductService -
public List<Product> getProductsByText(String searchText){
return db.findAllByAnyColumnContaining(searchText.toLowerCase());
}
I have used the findAllByAnyColumnContaining() method where I have a query
Output result -
SELECT p FROM Product p WHERE LOWER(p.name) LIKE %:searchText% OR LOWER(p.type) LIKE %:searchText% OR LOWER(p.place) LIKE %:searchText%
Where I have searched in columns "name, type, place" as these are string data types.
I have used the LOWER() to handle lowercase scenarios and I am converting the search string to lowercase first before passing it to the findAllByAnyColumnContaining method.
It returns the list of matching data.
Output result -
Assignment 3: Search for out-of-warranty products
I have used the findByWarrantyLessThan() method which takes the current year as an argument and provides the list of products having a warranty less than the current year.
public static void getOutOfWarranty(ProductService service){
List<Product> products = service.getOutOfWarranty(2023);
System.out.println("Out of warranty products");
for(Product p : products){
System.out.println(p);
}
}
ProductService -
public List<Product> getOutOfWarranty(Integer warranty){
return db.findByWarrantyLessThan(warranty);
}
Output result -