Home > Software design >  PostMapping passing Object with oneToMany relationship | Java spring-boot
PostMapping passing Object with oneToMany relationship | Java spring-boot

Time:11-17

I am new to spring boot. I have a class Comment which has a oneToMany relationship to the class User. Now I want to create a Comment with a post request. But how can I pass only the userId of the user who writes the comment? So I can save this Object to the database.

I hope somebody could help me with this. I would appreciate it.

Post Request:

{
    "message": "This is a message",
    "writer_id": 1
}

User

@Entity
@Table(name="tbl_users")
public class User {
    
    @Id
    @GeneratedValue(
            strategy = GenerationType.AUTO,
            generator = "user_sequence"
            )
    @SequenceGenerator(
            name = "user_sequence",
            allocationSize = 1,
            sequenceName = "user_sequence"
            )
    private Long id;
    private String name;
    public User(String name) {
        this.name = name;
    }
    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }
    public User() {
    }
    
    getter, setter ...

Comment

@Entity
@Table(name="tbl_comments")
public class Comment {
    
    @Id
    @GeneratedValue(
            strategy = GenerationType.AUTO,
            generator = "comment_sequence"
            )
    @SequenceGenerator(
            name = "comment_sequence",
            allocationSize = 1,
            sequenceName = "comment_sequence"
            )
    private Long id;
    private String message;
    @ManyToOne
    @JoinColumn(name="user_id", nullable=false)
    private User writer;
    
    public Comment(String message, User writer) {
        this.message = message;
        this.writer = writer;
    }

    public Comment(Long id, String message, User writer) {
        this.id = id;
        this.message = message;
        this.writer = writer;
    }

    public Comment() {
    }

    getter, setter...

CommentController

@PostMapping
    public void createComment(@RequestBody Comment comment) {
        commentService.createComment(comment);
    }

CommentService

public void createComment(Comment comment) {
        if(!userRepository.existsById(comment.getWriter().getId())) {
            throw new UserNotFoundException("Writer does not exist");
        }
        commentRepository.save(comment);
    }

CodePudding user response:

Here are some steps to follow : What I did here is basic implementation because I did not consider if the User was authenticated or not.

1- Add the following relation to the User entity

public class User {
  /**
    other attributes
  **/

 //relation with comment
 @OneToMany(cascade = CascadeType.ALL,
        fetch = FetchType.LAZY, orphanRemoval = true,
        mappedBy = "user")
 private Set<Comment> comments;
}

2- Then you should add the relation to the Comment entity also:

 public class Comment {
  /**
   other attributes
   **/

  //relation with user
  @ManyToOne()
  @JoinColumn(name = "user_id")
  private User user;
}

3- At the comment service just add userId as a parameter to your function

 public class CommentService {
 private CommentRepository commentRepository;
 private UserRepository userRepository;
 public Comment userPostComment(Comment comment, Long userId){
    User user = userRepository.findById(userId).orElseThrow(
                  () -> new UsernameNotFoundException("User not found"));
    /**
        set other attributes
     **/
    //add found user to the comment
    comment.setUser(user);
    return commentRepository.save(comment);
}

4- Finally at your controller, you should give userId as a PathVariable

 public class CommentController {
 private CommentService commentService;

 @PostMapping("/addComment/{userId}")
 public ResponseEntity<Comment> addComment(@RequestBody Comment comment,
                                          @PathVariable Long userId){
    return new ResponseEntity<>(
                         commentService.userPostComment(comment, userId), 
                         HttpStatus.CREATED);
  }
}

CodePudding user response:

One of the solutions is to create a CommentRequest class

public class CommentRequest {
   private String message;
   private int userId;

   getters, setters

}

Then in the CommentController you should change the method to:

@PostMapping
public void createComment(@RequestBody CommentRequest commentRequest) {
    commentService.createComment(commentRequest);
}

And also in the CommentService:

public void createComment(CommentRequest commentRequest) {
        if(!userRepository.existsById(commentRequest.getUserId())) {
            throw new UserNotFoundException("Writer does not exist");
        }
        User user = userRepository.getById(commentRequest.getUserId());
        commentRepository.save(new Comment(commentRequest.getMessage(), user));
    }
  • Related