【问题标题】:How to test Spring boot one to many JPA post request by curl o postman如何通过 curl o postman 测试 Spring Boot 一对多 JPA 发布请求
【发布时间】:2020-11-04 18:02:21
【问题描述】:

在我的 spring boot 应用程序中,我有以下模型:-

@Entity
@Table(name = "STUDENT")
public class Student {

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

    @Column
    private String name;

    @Column
    private int mobile;

    public Student() {

    }

    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "DEPT_ID", nullable = false)
    private Department department;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMobile() {
        return mobile;
    }

    public void setMobile(int mobile) {
        this.mobile = mobile;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", mobile=" + mobile +
                ", department=" + department +
                '}';
    }
}

    @Entity
@Table(name = "DEPARTMENT")
@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")
public class Department {

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

    @Column
    private String name;

    public Department() {

    }

    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    @OneToMany(mappedBy = "department", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<Student> studentList = new ArrayList<>();

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }
}


@RestController
public class StudentController {

    @Autowired
    StudentService studentService;

    @Autowired
    DepartmentService departmentService;

    @RequestMapping(value = "/studentList", method = RequestMethod.GET)
    public @ResponseBody
    List<Student> getStudents(){
        return studentService.getStudents();
    }

    @PostMapping("/saveStudent/{deptName}")
    public String saveStudent(@RequestBody List<Student> studentList, @PathVariable String deptName){
        try {
            Department dept = departmentService.findDepartment(deptName.toUpperCase());

            for(Student student: studentList)
                student.setDepartment(dept);

            studentService.saveStudent(studentList);
            return "Student saved successfully..";
        }catch (Exception ex){
            ex.printStackTrace();
            return "Error in saving Student ..";
        }
    }
}

对于上述应用程序。我想测试它的后控制器localhost:8080 /saveStudent/hr
请注意,我已经保存了人力资源部门。我厌倦了 Postman 的 JSON:-

{
"student": [{ "name": "masi",
"mobile": 12345,
"department": "hr"
}, { "name": "masi2",
"mobile": 1234500,
"department": "hr"
}]
}

我收到以下错误:-

已解决 [org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:无法从 START_OBJECT 令牌中反序列化 java.util.ArrayList&lt;com.example.onetomany.model.Student&gt; 的实例;嵌套异常是 com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize of java.util.ArrayList&lt;com.example.onetomany.model.Student&gt; out of START_OBJECT token 在 [来源:(PushbackInputStream);行:1,列:1]]

邮递员控制台日志:-

POST http://localhost:8080 /saveStudent/hr
400
183 ms
Network
Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.26.1
Accept: */*
Cache-Control: no-cache
Postman-Token: 57071c5d-e416-4b54-870a-9f318fee7166
Host: localhost:8080 
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 160
Request Body
Response Headers
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 15 Jul 2020 09:05:43 GMT
Connection: close
Response Body
{"timestamp":"2020-07-15T09:05:43.864+00:00","status":400,"error":"Bad Request","message":"","path":"/saveStudent/hr"}

我认为我的应用程序运行正常。如何通过 Postman 或 CURL 发出正确的 JSON 请求?

【问题讨论】:

  • 你能分享你的控制器代码吗,我想看看你是如何接受帖子正文的?
  • 我的问题中有 StudentController。我想测试@PostMapping("/saveStudent/{deptName}") public String saveStudent(@RequestBody List&lt;Student&gt; studentList, @PathVariable String deptName){ 控制器。另外,我添加了邮递员控制台日志。

标签: java json spring-boot postman


【解决方案1】:

你不应该在帖子正文中添加student 像下面这样使用

 [
  {
    "name": "masi",
    "mobile": 12345,
    "department": {
      "field":"value"
    }
  },
  {
    "name": "masi2",
    "mobile": 1234500,
     "department": {
      "field":"value"
    }
  }
]

不知道系类的字段,请相应编辑

【讨论】:

  • 当我尝试这个时。我收到此错误:- 已解决 [org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:无法从字符串“hr”反序列化 java.lang.Long 类型的值:不是有效的长值;嵌套异常是 com.fasterxml.jackson.databind.exc.InvalidFormatException:无法从字符串“hr”反序列化 java.lang.Long 类型的值:在 [Source: (PushbackInputStream); 处不是有效的 Long 值; line: 5, column: 19] (通过引用链: java.util.ArrayList[0]->com.example.onetomany.model.Student["department"])]
  • 在上述错误之后:- 我厌倦了这个[ { "name": "masi", "mobile": 12345, "department": "1" }, { "name": "masi2", "mobile": 1234500, "department": "1" } ]
  • 然后错误:.w.s.m.s.DefaultHandlerExceptionResolver:已解决 [org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:未解决的前向引用:;嵌套异常是 com.fasterxml.jackson.databind.deser.UnresolvedForwardReference: Unresolved forward references for: at [Source: (PushbackInputStream); line: 12, column: 1]Object id [1] (for com.example.onetomany.model.Department) at [Source: (PushbackInputStream); line: 5, column: 22], Object id [1] (for com.example.onetomany.model.Department) at [Source: (PushbackInputStream);
  • 部门是一个对象,就像我为学生所做的那样,你需要对部门也是如此。
  • 我更新了答案,请立即检查并编辑侧部门中的字段值
猜你喜欢
  • 2020-12-09
  • 2020-11-29
  • 2017-12-08
  • 2017-11-21
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
相关资源
最近更新 更多