Sobes.tech
Junior — Middle

Is it possible to implement the execution of an SQL query inside a data repository?

sobes.tech AI

Answer from AI

Yes, executing SQL queries within a data repository is a standard practice. The repository is responsible for interacting with the database, so it typically implements methods that execute SQL queries (via JDBC, JPA, Hibernate, or other ORM). This isolates data access logic from business logic.

Example in Java using JDBC:

public class UserRepository {
    private DataSource dataSource;

    public UserRepository(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public User findById(int id) throws SQLException {
        String sql = "SELECT * FROM users WHERE id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, id);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return new User(rs.getInt("id"), rs.getString("name"));
            }
            return null;
        }
    }
}