Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 310a6e5

Browse files
code refactor
1 parent 9faafc6 commit 310a6e5

File tree

3 files changed

+8
-9
lines changed

3 files changed

+8
-9
lines changed

‎jpa-one-to-many-demo/src/main/java/com/example/jpa/controller/CommentController.java‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,13 +53,9 @@ public Comment updateComment(@PathVariable (value = "postId") Long postId,
5353
@DeleteMapping("/posts/{postId}/comments/{commentId}")
5454
public ResponseEntity<?> deleteComment(@PathVariable (value = "postId") Long postId,
5555
@PathVariable (value = "commentId") Long commentId) {
56-
if(!postRepository.existsById(postId)) {
57-
throw new ResourceNotFoundException("PostId " + postId + " not found");
58-
}
59-
60-
return commentRepository.findById(commentId).map(comment -> {
61-
commentRepository.delete(comment);
62-
return ResponseEntity.ok().build();
63-
}).orElseThrow(() -> new ResourceNotFoundException("CommentId " + commentId + " not found"));
56+
return commentRepository.findByIdAndPostId(commentId, postId).map(comment -> {
57+
commentRepository.delete(comment);
58+
return ResponseEntity.ok().build();
59+
}).orElseThrow(() -> new ResourceNotFoundException("Comment not found with id " + commentId + " and postId " + postId));
6460
}
6561
}

‎jpa-one-to-many-demo/src/main/java/com/example/jpa/controller/PostController.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
public class PostController {
1616

1717
@Autowired
18-
PostRepository postRepository;
18+
privatePostRepository postRepository;
1919

2020
@GetMapping("/posts")
2121
public Page<Post> getAllPosts(Pageable pageable) {

‎jpa-one-to-many-demo/src/main/java/com/example/jpa/repository/CommentRepository.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,13 @@
66
import org.springframework.data.jpa.repository.JpaRepository;
77
import org.springframework.stereotype.Repository;
88

9+
import java.util.Optional;
10+
911
/**
1012
* Created by rajeevkumarsingh on 21/11/17.
1113
*/
1214
@Repository
1315
public interface CommentRepository extends JpaRepository<Comment, Long> {
1416
Page<Comment> findByPostId(Long postId, Pageable pageable);
17+
Optional<Comment> findByIdAndPostId(Long id, Long postId);
1518
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /