有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Springboot如何在JavaSpringBoot中创建列表?

我不熟悉java和springboot。我正在尝试使用springboot创建一个CRUD应用程序。 我使用MySQL存储数据

员工模式-

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

}

员工资源库-

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> {

}

员工控制员-

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

}

上面的控制器在JSON对象数组表单中给出了结果,如下所示

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

但我需要以下表格的回复

{
    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"
        }
    }
}

非常感谢你的帮助


共 (2) 个答案

  1. # 1 楼答案

    只需将结果封装在DTO类中,并将其与响应一起传递回去

    total_items-可以通过存储库返回的列表的大小来推断

    has_more-如果您将findAll()与存储库调用一起使用,那么您将获得数据库中的所有员工。否则,可能需要在存储库中引入分页

    employees将员工纳入Map

    回应

    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
    }
    

    雇员管制员

    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;
        }
    
    }
    
  2. # 2 楼答案

    您应该创建EmployeeResponse模型(根据需要更改名称)。 添加所需的其他字段。 可使用列表计算总的_项。大小()。 对于另一个字段,我将向数据库添加一个额外的查询,用于计算行数,例如按id列。 如果大于100,则进行比较,并将字段设置为true

    您可以在这里看到示例:Does Spring Data JPA have any way to count entites using method name resolving?

    如果在“findAll”方法中,您没有限制为100行,并且您实际上获得了所有员工,然后移动除100之外的所有员工,那么您可以设置此字段,而无需额外的计数查询