0

I am new to java and springboot. I am trying to create one CRUD application using springboot. I am using MySQL for storing the data.

Employee Model -

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employees")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email_id")
    private String emailId;

    public Employee() {
    }

    public Employee(String firstName, String lastName, String emailId) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.emailId = emailId;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

}

Employee Repository -

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

import com.raksh.springboot.model.Employee;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {

}

Employee Controller -

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.raksh.springboot.model.Employee;
import com.raksh.springboot.repository.EmployeeRepository;

@CrossOrigin(origins = "http://localhost:3000/")
@RestController
@RequestMapping("/api/v1/")
public class EmployeeController {

    @Autowired
    private EmployeeRepository employeeRepository;

    // get all employees
    @GetMapping("/employees")
    public List<Employee> getAllEmployees(){
        return employeeRepository.findAll();
    }

}

The above controller is giving me the result in the JSON array of objects form as shown below

[
  {
    "id": 1,
    "firstName": "Tony",
    "lastName": "Stark",
    "emailId": "tony@gmail.com"
  },
  {
    "id": 2,
    "firstName": "Thor",
    "lastName": "Odinson",
    "emailId": "thor@asgard.com"
  }
]

But I need the response in the below form

{
    total_items: 100,
    has_more: true,
    employees : {
        1 : {
            "id": 1,
            "firstName": "Raksh",
            "lastName": "Sindhe",
            "emailId": "raksh@gmail.com"
        },
        2: {
            "id": 2,
            "firstName": "Thor",
            "lastName": "Odinson",
            "emailId": "thor@asgard.com"
        }
    }
}

Really appreciate the help.

rakshian24
  • 33
  • 3
  • 9
  • either you need to add total_items and has_more fields to employee class and your mysql table or before returning from controller you can modify your object by creating a custom class which takes total_items, has_more and list of employee after fetching employees you can set total_items and has_more fields then return this custom class – tknkrtl Jul 05 '21 at 13:37
  • Checkout what Spring Data Rest could do for you https://docs.spring.io/spring-data/rest/docs/3.5.2/reference/html/#reference – Simon Martinelli Jul 05 '21 at 14:32
  • I think you can achieve this format using dto's, but you can also check out pagination. There is paging and sorting repository in JPA, it gives so much information. – isa_toltar Jul 05 '21 at 14:45

2 Answers2

2

You should create EmployeeResponse model (change the name as you see fit). Add the additional fields you require. The total_items could be calculated using list.size(). For the other field, I would add an additional query to the database for counting the number of rows, for example by id column. compare if it's more than 100 and set the field to true.

You can see example here: Does Spring Data JPA have any way to count entites using method name resolving?

If in the "findAll" method you don't limit to 100 rows and you actually get all the employees and then move all except 100, you can set this field without the additional count query.

yotam hadas
  • 702
  • 3
  • 14
1

Simply you need to encapsulate the results in a DTO class and pass it back with the response.

total_items - can be inferred by the size of the list returned by the repository.

has_more - If you are using findAll() with repository call then you would get all the employees in the DB. Otherwise, you might have to introduce pagination with the repository.

employees - Include employees in a Map

ResponseDTO

public class ResponseDTO {

    private int total_items;

    private boolean has_more;

    private Map<Integer, Employee> employees;

    public ResponseDTO(int totalItems, boolean hasMore, Map<Integer, Employee> employees) {
        this.total_items=totalItems;
        this.has_more=hasMore;
        this.employees=employees;
    }

    //constructors, getters, and setters
}

EmpoyeeController

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.raksh.springboot.model.Employee;
import com.raksh.springboot.repository.EmployeeRepository;

@CrossOrigin(origins = "http://localhost:3000/")
@RestController
@RequestMapping("/api/v1/")
public class EmployeeController {

    @Autowired
    private EmployeeRepository employeeRepository;

    // get all employees
    @GetMapping("/employees")
    public List<Employee> getAllEmployees(){

        Pageable employeePage = PageRequest.of(0, 100); //so you expect first 100 slice from all the employees in the DB.
        Page<Employee> employees = employeeRepository.findAll(employeePage);
        Map<Integer, Employee> employeeMap = getEmployeeMap(employees.getContent());
        
        return new ResponseDTO(employees.getNumberOfElements(),employees.hasNext(),employeeMap );
    }

    private Map<Integer, Employee> getEmployeeMap(List<Employee> empoyees){

        if(employees!=null && !empoyees.isEmpty){
            Map<Integer, Employee> employeeMap = new HashMap<>();
            for(Employee emp:empoyees){
                employeeMap.put(emp.getId(),emp);
            }
            return employeeMap;
        }
        return null;
    }

}
ThilankaD
  • 1,021
  • 1
  • 13
  • 24