【问题标题】:How to create list of list in Java Springboot?如何在 Java Spring Boot 中创建列表列表?
【发布时间】:2021-09-16 06:53:20
【问题描述】:

我是 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"
        }
    }
}

非常感谢您的帮助。

【问题讨论】:

  • 要么您需要将 total_items 和 has_more 字段添加到员工类和您的 mysql 表中,或者在从控制器返回之前,您可以通过创建一个自定义类来修改您的对象,该类在获取后获取 total_items、has_more 和员工列表员工,您可以设置 total_items 和 has_more 字段,然后返回此自定义类
  • 查看 Spring Data Rest 可以为您做什么docs.spring.io/spring-data/rest/docs/3.5.2/reference/html/…
  • 我认为您可以使用 dto 实现这种格式,但您也可以查看分页。 JPA中有分页和排序存储库,它提供了很多信息。

标签: java spring-boot api rest


【解决方案1】:

您应该创建 EmployeeResponse 模型(根据需要更改名称)。 添加您需要的其他字段。 total_items 可以使用 list.size() 计算。 对于另一个字段,我会在数据库中添加一个额外的查询来计算行数,例如按 id 列。 比较是否超过 100 并将该字段设置为 true。

您可以在此处查看示例:Does Spring Data JPA have any way to count entites using method name resolving?

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

【讨论】:

    【解决方案2】:

    只需将结果封装在 DTO 类中,并与响应一起传回即可。

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

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

    employees - 在Map 中包含员工

    响应DTO

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

    【讨论】:

      猜你喜欢
      • 2016-10-10
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多