Sobes.tech
Junior — Middle

What class or structure is used when developing REST API to retrieve information from a database?

sobes.tech AI

Answer from AI

When developing REST APIs in Java to retrieve information from a database, a class or structure that represents a data model (Entity) and a service layer for data access are often used.

For database operations, JPA (Java Persistence API) and entity classes are typically employed, for example:

@Entity
public class User {
    @Id
    private Long id;
    private String name;
    // getters and setters
}

To retrieve data, repositories are used, such as an interface extending JpaRepository:

public interface UserRepository extends JpaRepository<User, Long> {}

In the REST API controller, data can be obtained through a service:

@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
        return userRepository.findById(id).orElse(null);
    }
}

Thus, the key classes are Entity (e.g., User) and repositories (e.g., UserRepository) for retrieving information from the database.