Sobes.tech
Junior — Middle

What are the ways to implement a REST API for retrieving information from a database?

sobes.tech AI

Answer from AI

To implement a REST API in Java that retrieves information from a database, several approaches can be used:

  1. Using Spring Boot with Spring Data JPA:
    • Create entities corresponding to database tables.
    • Create repositories for data access.
    • Create controllers with methods handling HTTP requests (GET, POST, etc.).

Example controller:

@RestController
@RequestMapping("/api/users")
public class UserController {
    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return userRepository.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }
}
  1. Using JAX-RS (e.g., with Jersey):

    • Create resources with @Path, @GET annotations.
    • Inside methods, access the database via DAO or ORM.
  2. Using plain JDBC:

    • Manually write SQL queries.
    • Process results and return data through controllers.

In practice, Spring Boot with Spring Data is most commonly used, as it simplifies development and database integration.