JPA中的CRUD多对一双向关系

时间:2018-12-19 21:30:16

标签: mysql spring-boot jpa crud bidirectional

我需要创建多对一关系,并且我不知道自己是否做对了,因为我无法正确进行更新和删除。我在Java中使用Spring Boot和JPA存储库,数据库是mysql。

我有一个带有名称的帖子,每个帖子可以有多个评论,但是我需要一起使用,如果要添加评论,则将带有新评论的帖子发送给该帖子,例如:

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

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

Comments.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);

}

Controller.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);
    }
}

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

0 个答案:

没有答案
相关问题