Home > other >  How to retrieve data in spring boot without passing any variable?
How to retrieve data in spring boot without passing any variable?

Time:12-30

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.

CodePudding user response:

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()

CodePudding user response:

I see several issues in your code, follow below steps to resolve.

  1. In your RestController class autowire 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

  1. Add @Service in the StudentService class.

  2. Remove static from both the methods in StudentService fetchAllStudentDeatil() and findStudentDetailByRollNo(rollNo).

  3. Finally in your RestController, use studentService.fetchAllStudentDeatil() and studentService.fetchAllStudentDeatil(rollNo)

  4. Optional, correct the typo in Deatil

CodePudding user response:

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.

  • Related