rakshian24
rakshian24

Reputation: 33

How to create list of list in Java Springboot?

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": "[email protected]"
  },
  {
    "id": 2,
    "firstName": "Thor",
    "lastName": "Odinson",
    "emailId": "[email protected]"
  }
]

But I need the response in the below form

{
    total_items: 100,
    has_more: true,
    employees : {
        1 : {
            "id": 1,
            "firstName": "Raksh",
            "lastName": "Sindhe",
            "emailId": "[email protected]"
        },
        2: {
            "id": 2,
            "firstName": "Thor",
            "lastName": "Odinson",
            "emailId": "[email protected]"
        }
    }
}

Really appreciate the help.

Upvotes: 0

Views: 7964

Answers (2)

ThilankaD
ThilankaD

Reputation: 1099

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;
    }

}

Upvotes: 1

yotam hadas
yotam hadas

Reputation: 863

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.

Upvotes: 2

Related Questions