HTTP GET method is commonly used to retrieve data from a server. It’s another operation of Spring CRUD Operation.
Http POST method used to store and read data from server example and implementation explained here
READ (R): Create RESTFul api to read data from server, We can use Http Get method to read the data from table. Here is basic step
Step 1: Create java file BookController.java and then put below code in controller, here we have created method call getBook() .
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.techbug.techbug.service.BookService; import com.techbug.techbug.vo.BookVO; @RestController public class BookController { @Autowired private BookService bookService; @GetMapping(value = "/readbook") public Object readBook() { return bookService.readBook(); } }
Step 2: Create Service file called BookService.java and define readBook() method, inside readBook() method we have used bookRepository.findAll(), findAll() is predefined hibernate method which fetch all records from table. @Autowired BookService bookService which allows to access all method which is declared BookService class.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.techbug.techbug.entity.Book; import com.techbug.techbug.repository.BookRepository; import com.techbug.techbug.vo.BookVO; @Service public class BookService { @Autowired private BookRepository bookRepository; public Object readBook() { return bookRepository.findAll(); } }
Step 3: Create an Interface and extend JPARepository inside interface and map table entity where data has to be stored or populated, each repository represents individual table entity.
import org.springframework.data.jpa.repository.JpaRepository; import com.techbug.techbug.entity.Book; public interface BookRepository extends JpaRepository<Book, Long>{ }
Step 4: Now run as java application and hit you end point using api validation tool, such as POSTMAN or Browser since its get method.
3 Replies to “Http Get Method Spring Boot Tutorial”