如何使用Spring Boot通过方法post在postman中发送2个不同的对象?

时间:2019-05-07 13:11:44

标签: java hibernate spring-boot

我正在控制器中编写一个函数,该函数应该将对象“ Post”添加到另一个对象“ Topic”的属性中,该对象是一个数组列表。该功能所需的参数是“ Post”(p)和“ Topic”的id(topicID)。我想知道如何用邮递员寄给他们。

当我尝试通过填写邮递员的'Post'+ topicID of'Topic'的所有参数来发送它们时,出现如下错误消息。

控制器中的功能:

@RestController
@RequestMapping("/TopicController")
public class TopicController {
    @Autowired
    TopicRepository topicRepository;
    @Autowired
    PostRepository postRepository;

@RequestMapping(method = RequestMethod.POST, value = "/AddPost")
    public void addPost(Post p, @RequestParam(value="topicID") int topicID) {
        if (topicRepository.existsById(topicID)) {
            Optional<Topic> ot = topicRepository.findById(topicID);
            Topic t = ot.get();
            t.addPost(p);
            p.setTopic(t.getName());
            postRepository.save(p);
            topicRepository.save(t);
        }
    }
}

课堂帖子:

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String topic;
    private String title;
    @Temporal(TemporalType.TIMESTAMP)
    private Date posteDate;
    private String auther;
    @Lob
    private String content;
    private int readTimes;

    public void setTopic(String topic) {
        this.topic = topic;
    }
}

课程主题:

@Entity
public class Topic {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(unique=true)
    private String name;
    @Lob
    private String presentation;

    private ArrayList<String> coverPhotos;
    private ArrayList<Post> posts;

    public void addPost(Post post) {
        this.posts.add(post);
    }

    public void setPosts(ArrayList<Post> posts) {
        this.posts = posts;
    }

}

错误消息:

2019-05-07 11:56:22.907 ERROR 24900 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null

2 个答案:

答案 0 :(得分:0)

您需要先创建数组,然后再使用.add(),像这样更改您的addPost():

public void addPost(Post post) {
    if(posts == null) posts = new ArrayList<>();
    this.posts.add(post);
}

答案 1 :(得分:0)

您在控制器方法中缺少@RequestBody批注。 您的控制器方法应如下所示,这样主体将被映射到Post对象,而查询参数topicId将被映射到topicId对象。

public void addPost(@RequestBody Post p, @RequestParam(value="topicID") int topicID)