crud

qeeaahzv  于 2021-06-15  发布在  Mysql
关注(0)|答案(0)|浏览(310)

我需要创建一个多对一的关系,我不知道我做得是否正确,因为我不能做正确的更新和删除。我在java中使用springboot和jpa存储库,数据库是mysql。
我有一个带有名字的帖子,每个帖子都可以有几个评论,但是我需要一起使用,如果我想添加评论,我会用新的评论发送帖子,例如:

{
    "name":"PostName",
    "comment: [
        {
            "text":"comment 1"
        },
        {
            "text":"comment 2"
        }
    ]
}

后java

@Entity
public class Post {

    @Id
    @Column(name = "Post")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

    @OneToMany(cascade = CascadeType.ALL,
            fetch = FetchType.LAZY,
            mappedBy = "post")
    private List<Comments> Comments = new ArrayList<>();

    // Get and Set

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

注解.java

@Entity
public class Comments {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String text;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id")
    @JsonIgnore
    private Post post;

    // Get and Set

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
}

postrepository.java文件

public interface PostRepository extends JpaRepository<Post, Long> {

    Club findByName(@Param("name") String name);

}

控制器.java

@Autowired
PostRepository postRepository;

@RequestMapping(value="/posts", method=RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getPost(Pageable pageable){
    try {
        Page<Post> posts = postRepository.findAll(pageable);    
        return new ResponseEntity<>(posts,HttpStatus.ACCEPTED);

    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
    }
}

@RequestMapping(value="/newPost", method=RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> newPost(@RequestBody Post post){

    try {

        for (Comments comments: post.getComments()){
            comments.setPost(post);
        }

        postRepository.save(post);
        return new ResponseEntity<>(HttpStatus.CREATED);

    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
    }
}

我不知道我的工作是否正确,我需要更新和删除方法。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题