Hackforge Academy

Category: java

get user list from DB and return response

Published on 20 Apr 2026

Explanation

Define a User entity mapped to the database table using JPA annotations.

Code:

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = 
GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    // getters and setters
}

Explanation

Create a repository interface extending JpaRepository to fetch user records from the database.

Code:

import org.springframework.data.jpa.
repository.JpaRepository;

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

Explanation

Service layer contains business logic and calls repository methods like findAll().

Code:

@Service
public class UserService {

    private final UserRepository 
userRepository;

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

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

Explanation

Expose REST API endpoint to return the list of users as JSON response.

Code:

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService 
userService) {
        this.userService = userService;
    }

    @GetMapping
    public List<User> getUsers() {
        return userService.getAllUsers();
    }
}

Explanation

Example JSON response returned when calling GET /api/users endpoint.

Code:

[
  {
    "id": 1,
    "name": "hackforge",
    "email": "hackforge@gmail.com"
  },
  {
    "id": 2,
    "name": "academy",
    "email": "academy@gmail.com"
  }
]

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community