{
// Custom query methods if needed
Page
// Entity class
@Entity
@Table(name = "food_items")
public class FoodItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String category;
private Double price;
// Getters, setters, and constructors
}
// Repository interface
@Repository
public interface FoodItemRepository extends JpaRepository<FoodItem, Long> {
// Custom query methods if needed
Page<FoodItem> findByCategory(String category, Pageable pageable);
}
// Service class
@Service
public class FoodItemService {
@Autowired
private FoodItemRepository foodItemRepository;
public Page<FoodItem> getAllFoodItems(int page, int size, String sortBy, String direction) {
Sort sort = Sort.by(Sort.Direction.fromString(direction), sortBy);
Pageable pageable = PageRequest.of(page, size, sort);
return foodItemRepository.findAll(pageable);
}
public Page<FoodItem> getFoodItemsByCategory(String category, int page, int size, String sortBy, String direction) {
Sort sort = Sort.by(Sort.Direction.fromString(direction), sortBy);
Pageable pageable = PageRequest.of(page, size, sort);
return foodItemRepository.findByCategory(category, pageable);
}
}
// Controller class
@RestController
@RequestMapping("/api/food-items")
public class FoodItemController {
@Autowired
private FoodItemService foodItemService;
@GetMapping
public ResponseEntity<Map<String, Object>> getAllFoodItems(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "name") String sortBy,
@RequestParam(defaultValue = "ASC") String direction) {
Page<FoodItem> foodItems = foodItemService.getAllFoodItems(page, size, sortBy, direction);
Map<String, Object> response = new HashMap<>();
response.put("items", foodItems.getContent());
response.put("currentPage", foodItems.getNumber());
response.put("totalItems", foodItems.getTotalElements());
response.put("totalPages", foodItems.getTotalPages());
return ResponseEntity.ok(response);
}
@GetMapping("/category/{category}")
public ResponseEntity<Map<String, Object>> getFoodItemsByCategory(
@PathVariable String category,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "name") String sortBy,
@RequestParam(defaultValue = "ASC") String direction) {
Page<FoodItem> foodItems = foodItemService.getFoodItemsByCategory(category, page, size, sortBy, direction);
Map<String, Object> response = new HashMap<>();
response.put("items", foodItems.getContent());
response.put("currentPage", foodItems.getNumber());
response.put("totalItems", foodItems.getTotalElements());
response.put("totalPages", foodItems.getTotalPages());
return ResponseEntity.ok(response);
}
}