Issue
I'm writing REST service.
I want to get all records by date that I pass in @Path variable.
How Can I do that?
What I tried to do:
Model Class:
@Entity
@Table(name = "test")
public class Test {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate beginDate;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate endDate;
private String activity;
}
Repository:
@Repository
public interface TestRepository extends JpaRepository<Test, Integer> {
List<Test> findAllByName(String name);
List<Test> findAllByBeginDate(LocalDate date);
}
Service:
@Service
public class TestService {
@Autowired
private final TestRepository testRepository;
public TestService(TestRepository testRepository) {
this.testRepository = testRepository;
}
public List<Test> getAllTestsByBeginDate(LocalDate date) {
return testRepository.findAllByBeginDate(date);
}
}
Controller:
@RestController
@RequestMapping("/api/v1/")
public class TestController {
@GetMapping("test/all/{date}")
public List<Test> getAllTestsByBeginDate(@PathVariable ("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
return testService.getAllTestsByBeginDate(date);
}
}
When I pass date like this, I get errors:
Solution
This should work
@RestController
@RequestMapping("/api/v1/")
public class TestController {
@GetMapping("test/all/{date}")
public List<Test> getAllTestsByBeginDate(@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
return testService.getAllTestsByBeginDate(date);
}
}
or this link will help
Answered By - Swarit Agarwal
Answer Checked By - Terry (JavaFixing Volunteer)