Reputation: 11
When I don't specify any date, I want to return all reservations.
I have a controller where a RequestParam
is used:
public List<resrvation> getAll(@RequestParam(name = "date1",required = false)) String date1,@RequestParam(name = "date2",required = false)) String date2){
return resrvationService.getAll( date1,date2);
}
My DAO:
Query("select DISTINCT r from reservation where r.dateRv between :date1 and :date2")
public List<Reservation> getAll(@Param("date1") Date date1, @Param("date2") Date date2);
}
Upvotes: 1
Views: 807
Reputation: 14572
Keep it simple, create two methods :
public List<Reservation> getAll():
public List<Reservation> getAll(Date, Date):
And in the controller, based on the parameter your received, call one or the other. Here is a simple example :
public List<reservation> getAll(
@RequestParam(name = "date1", required = false) String date1,
@RequestParam(name = "date2", required = false) String date2) {
return (date1 == null && date2 == null) ?
reservationService.getAll() :
reservationService.getAll(date1, date2);
}
Upvotes: 1
Reputation: 156
Its very hard to answer your question without knowing what is your application technical stack is. If you are using Java8, You can also use optional for request parameters. Also try using spring-data-jpa derived queries on JPA repositories to get what you want.
public List<resrvation> getAll(@RequestParam(name = "date1",required = false)) Optional<String> startDate,@RequestParam(name = "date2",required = false)) Optional<String> date2){
if(date1.isPresent() && date2.isPresent()) {
return reservationService.findAllBetweenStartDateAndEndDate( date1.get(),date2.get());
} else {
return reservationService.findAll();
}
}
And On repositories
List<Reservation> findAll();
List<Reservation> findByDateBetween(Date startDate, Date endDate);
Upvotes: 0
Reputation: 80
If you want to return all data if date is null then u can do something like this:
select DISTINCT r from reservation where
(:date1 is null or r.dateRv >= trunc(:date1 )) and
(:date2 is null or r.dateRv <= trunc(:date2))
use of trunc function is upto you
Upvotes: 0