Reputation: 89
How to retrieve a list of data in spring boot without passing any variable. We are passing only URL for the GET request.
For example, in below code I am passing "roll no" and it is working fine, it is fetching corresponding student detail.
@GetMapping{"/fetch/{rollNo}")
public List<StudentDetail> findStudentDeatilbyRollNo (@PathVariable String rollNo){
return StudentService.findStudentDetailByRollNo(rollNo);
}
But when I want to fetch all student data without passing parameter it is giving me error "Non-static method 'fetchAllStudentDetail()' can not be referenced from a static context"
@GetMapping{"/allStudentDetails")
public List<StudentDetail> fetchAllStudentDeatil(){
return StudentService.fetchAllStudentDeatil();
}
Someone, please help me with the problem.
Upvotes: 0
Views: 911
Reputation: 183
I see several issues in your code, follow below steps to resolve.
StudentService
.Example 1:
@Autowired private StudentService studentService;
Example 2:
private final StudentService studentService; @Autowired public RestControllerClassName(StudentService studentService){ this.studentService = studentService; }
Read more: Spring @Autowire on Properties vs Constructor
Add @Service
in the StudentService
class.
Remove static from both the methods in StudentService
fetchAllStudentDeatil()
and findStudentDetailByRollNo(rollNo)
.
Finally in your RestController, use studentService.fetchAllStudentDeatil()
and studentService.fetchAllStudentDeatil(rollNo)
Optional, correct the typo in Deatil
Upvotes: 1
Reputation: 1726
The error means that you are trying to call a non static method in a static way :
To fix that, try to make this method static.
StudentService.fetchAllStudentDeatil()
To make it static you add the static word
public static List<StudentDetail> fetchAllStudentDeatil()
Upvotes: 1
Reputation: 1015
you need to define the function fetchAllStudentDeatil inside student service where you are retrieving all the entries in your table ;
static List<Student> fetchAllStudentDeatil { return studentRepo.findAll(); }
Also make sure that the method on GetMapping is not static . In case it is, make the fetchAllStudentDeatil also static.
Upvotes: 0