I want to build a search functionality in my application. There are many parameters which can be optional.
Model
@Getter
@Setter
@EqualsAndHashCode(exclude = "inventoryInspectionReport")
@NoArgsConstructor
@Entity()
public class Inventory {
@SequenceGenerator(
name = "car_inventory_sequence",
sequenceName = "car_inventory_sequence",
allocationSize = 1
)
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "car_inventory_sequence"
)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String owner;
@Column(nullable = false)
private String km_driven;
@Column(nullable = false)
private Integer price;
@Column
private String fuelType;
@Column
private String location;
@Column
private String insuranceValidity;
@Column
private String rto;
}
Controller
@GetMapping("/buy-car")
public String showBuyCarPageList(Model model,
@RequestParam("page") Optional<Integer> page,
@RequestParam("size") Optional<Integer> size
){
int currentPage = page.orElse(1);
int pageSize = size.orElse(16);
Page<Inventory> pageObj = carInventoryService.listAllCarIfShow(currentPage, pageSize);
int totalPages = pageObj.getTotalPages();
long totalItems = pageObj.getTotalElements();
List<Inventory> carInventoryList = pageObj.getContent();
model.addAttribute("currentPage", 1);
model.addAttribute("totalPages", totalPages);
model.addAttribute("totalItems", totalItems);
model.addAttribute("carInfo", carInventoryList);
return "frontend/buy-car-list";
}
@Service
@AllArgsConstructor
public class InventoryServiceImpl implements InventoryService {
@Autowired
private Environment env;
InventoryRepository carInventoryRepository;
InventoryImagesRepository carInventoryImagesRepository;
@Override
public Page<Inventory> listAllCarIfShow(int pageNumber, int pageSize) {
Pageable pageable = PageRequest.of(pageNumber - 1, pageSize);
return carInventoryRepository.findAllByShow(true, pageable);
}
}
My question is, how i can create a search functionality? There can be some parameter null? How i can query or ignore the parameters?
Bellow is query samples
http://localhost:8080/buy-car?page=1&size=1&name=Car2
http://localhost:8080/buy-car?page=1&size=1&name=Car2&owner=1st
http://localhost:8080/buy-car?page=1&size=1&fuelType=Petrol&owner=1st
CodePudding user response:
Assuming that you are using JPA. You can handle it by writing a query as below. This will ignore the where condition if the parameter is null.
@Repository
public class InventoryRepository extends JPARepository<Inventory, Long> {
@Query("SELECT i FROM Inventory i WHERE (:name is null or i.name = :name) and (:owner is null or i.owner = :owner)")
Page<Inventory> findAllByShow (String name, String owner, Pageable pageable);
}
PS: You need to update your Controller
and Service
layers to accept other parameters such as name, owner etc..