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

标签 java hibernate spring-boot

我正在 Controller 中编写一个函数,该函数应该将对象“Post”添加到另一个对象“Topic”的属性中,该对象是一个数组列表。该函数所需的参数是“Post”(p) 和“Topic”的 id (topicID)。我想知道如何在 Postman 中发送它们。

当我尝试通过在 Postman 中填写“Post”+“Topic”的 topicID 的所有参数来发送它们时,收到如下错误消息。

Controller 中的功能:

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

类(class)帖子:

@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

最佳答案

您需要在使用 .add() 之前创建数组,如下更改 addPost() :

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

关于java - 如何使用Spring boot通过post方法在postman中发送2个不同的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56023414/

相关文章:

java - 在 Spring Boot 中连接到任何一个数据库

java - 子类的参数可以比它的子类少吗?

java - 排除tomcat的jars lib目录

java - UTF-8 规范化重音编码形式之间的冲突

java - JPA : @PrimaryKeyJoinColumn or @JoinColumn + @Id

spring-boot - 轴突事件溯源的理解

java - 在GKE集群中运行的Java应用程序如何以编程方式应用yaml文件?

mysql - hibernate 正则表达式 MySQL

java - Mysql错误: field 'XXX' doesn't have a default value

java - 使用 Spring Boot 1.5 避免 Kafka Streams 在测试中启动