Skip to content

Commit d04a918

Browse files
author
Rajeev Kumar Singh
committed
Jpa One To Many Demo with Rest APIs
1 parent 69ba755 commit d04a918

File tree

10 files changed

+192
-103
lines changed

10 files changed

+192
-103
lines changed
-46.5 KB
Binary file not shown.

jpa-one-to-many-demo/.mvn/wrapper/maven-wrapper.properties

Lines changed: 0 additions & 1 deletion
This file was deleted.
Lines changed: 3 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,13 @@
11
package com.example.jpa;
22

3-
import com.example.jpa.model.Comment;
4-
import com.example.jpa.model.Post;
5-
import com.example.jpa.repository.CommentRepository;
6-
import com.example.jpa.repository.PostRepository;
7-
import org.springframework.beans.factory.annotation.Autowired;
8-
import org.springframework.boot.CommandLineRunner;
93
import org.springframework.boot.SpringApplication;
104
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
116

127
@SpringBootApplication
13-
public class JpaOneToManyDemoApplication implements CommandLineRunner {
14-
15-
@Autowired
16-
private PostRepository postRepository;
17-
18-
@Autowired
19-
private CommentRepository commentRepository;
20-
8+
@EnableJpaAuditing
9+
public class JpaOneToManyDemoApplication {
2110
public static void main(String[] args) {
2211
SpringApplication.run(JpaOneToManyDemoApplication.class, args);
2312
}
24-
25-
@Override
26-
public void run(String... args) throws Exception {
27-
// Cleanup Database tables
28-
commentRepository.deleteAllInBatch();
29-
postRepository.deleteAllInBatch();
30-
31-
// ======================================
32-
33-
Post post = new Post("Hibernate One-To-Many Mapping Example",
34-
"Learn how to use one to many mapping in hibernate",
35-
"Entire Post Content with sample code");
36-
37-
Comment comment1 = new Comment("Great Post!");
38-
comment1.setPost(post);
39-
40-
Comment comment2 = new Comment("Really helpful Post. Thanks a lot!");
41-
comment2.setPost(post);
42-
43-
post.getComments().add(comment1);
44-
post.getComments().add(comment2);
45-
46-
postRepository.save(post);
47-
48-
// ======================================
49-
50-
}
5113
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.example.jpa.controller;
2+
3+
import com.example.jpa.exception.ResourceNotFoundExcption;
4+
import com.example.jpa.model.Comment;
5+
import com.example.jpa.repository.CommentRepository;
6+
import com.example.jpa.repository.PostRepository;
7+
import org.springframework.beans.factory.annotation.Autowired;
8+
import org.springframework.data.domain.Page;
9+
import org.springframework.data.domain.PageRequest;
10+
import org.springframework.data.domain.Pageable;
11+
import org.springframework.data.domain.Sort;
12+
import org.springframework.http.ResponseEntity;
13+
import org.springframework.web.bind.annotation.*;
14+
15+
import javax.validation.Valid;
16+
import java.util.List;
17+
18+
@RestController
19+
public class CommentController {
20+
21+
@Autowired
22+
private CommentRepository commentRepository;
23+
24+
@Autowired
25+
private PostRepository postRepository;
26+
27+
@GetMapping("/posts/{postId}/comments")
28+
public Page<Comment> getAllCommentsByPostId(@PathVariable (value = "postId") Long postId,
29+
Pageable pageable) {
30+
return commentRepository.findByPostId(postId, pageable);
31+
}
32+
33+
@PostMapping("/posts/{postId}/comments")
34+
public Comment createComment(@PathVariable (value = "postId") Long postId,
35+
@Valid @RequestBody Comment comment) {
36+
return postRepository.findById(postId).map(post -> {
37+
comment.setPost(post);
38+
return commentRepository.save(comment);
39+
}).orElseThrow(() -> new ResourceNotFoundExcption("PostId " + postId + " not found"));
40+
}
41+
42+
@PutMapping("/posts/{postId}/comments/{commentId}")
43+
public Comment updateComment(@PathVariable (value = "postId") Long postId,
44+
@PathVariable (value = "commentId") Long commentId,
45+
@Valid @RequestBody Comment commentRequest) {
46+
if(!postRepository.existsById(postId)) {
47+
throw new ResourceNotFoundExcption("PostId " + postId + " not found");
48+
}
49+
50+
return commentRepository.findById(commentId).map(comment -> {
51+
comment.setText(commentRequest.getText());
52+
return commentRepository.save(comment);
53+
}).orElseThrow(() -> new ResourceNotFoundExcption("CommentId " + commentId + "not found"));
54+
}
55+
56+
@DeleteMapping("/posts/{postId}/comments/{commentId}")
57+
public ResponseEntity<?> deleteComment(@PathVariable (value = "postId") Long postId,
58+
@PathVariable (value = "commentId") Long commentId) {
59+
if(!postRepository.existsById(postId)) {
60+
throw new ResourceNotFoundExcption("PostId " + postId + " not found");
61+
}
62+
63+
return commentRepository.findById(commentId).map(comment -> {
64+
commentRepository.delete(comment);
65+
return ResponseEntity.ok().build();
66+
}).orElseThrow(() -> new ResourceNotFoundExcption("CommentId " + commentId + " not found"));
67+
}
68+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.example.jpa.controller;
2+
3+
import com.example.jpa.exception.ResourceNotFoundExcption;
4+
import com.example.jpa.model.Post;
5+
import com.example.jpa.repository.PostRepository;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.data.domain.Page;
8+
import org.springframework.data.domain.Pageable;
9+
import org.springframework.http.ResponseEntity;
10+
import org.springframework.web.bind.annotation.*;
11+
12+
import javax.validation.Valid;
13+
14+
@RestController
15+
public class PostController {
16+
17+
@Autowired
18+
PostRepository postRepository;
19+
20+
@GetMapping("/posts")
21+
public Page<Post> getAllPosts(Pageable pageable) {
22+
return postRepository.findAll(pageable);
23+
}
24+
25+
@PostMapping("/posts")
26+
public Post createPost(@Valid @RequestBody Post post) {
27+
return postRepository.save(post);
28+
}
29+
30+
@PutMapping("/posts/{postId}")
31+
public Post updatePost(@PathVariable Long postId, @Valid @RequestBody Post postRequest) {
32+
return postRepository.findById(postId).map(post -> {
33+
post.setTitle(postRequest.getTitle());
34+
post.setDescription(postRequest.getDescription());
35+
post.setContent(postRequest.getContent());
36+
return postRepository.save(post);
37+
}).orElseThrow(() -> new ResourceNotFoundExcption("PostId " + postId + " not found"));
38+
}
39+
40+
41+
@DeleteMapping("/posts/{postId}")
42+
public ResponseEntity<?> deletePost(@PathVariable Long postId) {
43+
return postRepository.findById(postId).map(post -> {
44+
postRepository.delete(post);
45+
return ResponseEntity.ok().build();
46+
}).orElseThrow(() -> new ResourceNotFoundExcption("PostId " + postId + " not found"));
47+
}
48+
49+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.example.jpa.exception;
2+
3+
import org.springframework.http.HttpStatus;
4+
import org.springframework.web.bind.annotation.ResponseStatus;
5+
6+
@ResponseStatus(HttpStatus.NOT_FOUND)
7+
public class ResourceNotFoundExcption extends RuntimeException {
8+
public ResourceNotFoundExcption() {
9+
super();
10+
}
11+
12+
public ResourceNotFoundExcption(String message) {
13+
super(message);
14+
}
15+
16+
public ResourceNotFoundExcption(String message, Throwable cause) {
17+
super(message, cause);
18+
}
19+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.example.jpa.model;
2+
3+
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
4+
import org.springframework.data.annotation.CreatedDate;
5+
import org.springframework.data.annotation.LastModifiedDate;
6+
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
7+
8+
import javax.persistence.*;
9+
import javax.validation.constraints.NotNull;
10+
import java.io.Serializable;
11+
import java.util.Date;
12+
13+
@MappedSuperclass
14+
@EntityListeners(AuditingEntityListener.class)
15+
@JsonIgnoreProperties(
16+
value = {"createdAt", "updatedAt"},
17+
allowGetters = true
18+
)
19+
public abstract class AuditModel implements Serializable {
20+
@Temporal(TemporalType.TIMESTAMP)
21+
@Column(name = "created_at", nullable = false)
22+
@CreatedDate
23+
private Date createdAt;
24+
25+
@Temporal(TemporalType.TIMESTAMP)
26+
@Column(name = "updated_at", nullable = false)
27+
@LastModifiedDate
28+
private Date updatedAt;
29+
30+
public Date getCreatedAt() {
31+
return createdAt;
32+
}
33+
34+
public void setCreatedAt(Date createdAt) {
35+
this.createdAt = createdAt;
36+
}
37+
38+
public Date getUpdatedAt() {
39+
return updatedAt;
40+
}
41+
42+
public void setUpdatedAt(Date updatedAt) {
43+
this.updatedAt = updatedAt;
44+
}
45+
}

jpa-one-to-many-demo/src/main/java/com/example/jpa/model/Comment.java

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.example.jpa.model;
22

3+
import com.fasterxml.jackson.annotation.JsonIgnore;
4+
35
import javax.persistence.*;
46
import javax.validation.constraints.NotNull;
57

@@ -8,7 +10,7 @@
810
*/
911
@Entity
1012
@Table(name = "comments")
11-
public class Comment {
13+
public class Comment extends AuditModel {
1214
@Id
1315
@GeneratedValue(strategy = GenerationType.IDENTITY)
1416
private Long id;
@@ -19,16 +21,9 @@ public class Comment {
1921

2022
@ManyToOne(fetch = FetchType.LAZY)
2123
@JoinColumn(name = "post_id", nullable = false)
24+
@JsonIgnore
2225
private Post post;
2326

24-
public Comment() {
25-
26-
}
27-
28-
public Comment(String text) {
29-
this.text = text;
30-
}
31-
3227
public Long getId() {
3328
return id;
3429
}

jpa-one-to-many-demo/src/main/java/com/example/jpa/model/Post.java

Lines changed: 1 addition & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,13 @@
33
import javax.persistence.*;
44
import javax.validation.constraints.NotNull;
55
import javax.validation.constraints.Size;
6-
import java.util.*;
76

87
/**
98
* Created by rajeevkumarsingh on 21/11/17.
109
*/
1110
@Entity
1211
@Table(name = "posts")
13-
public class Post {
12+
public class Post extends AuditModel {
1413
@Id
1514
@GeneratedValue(strategy = GenerationType.IDENTITY)
1615
private Long id;
@@ -28,31 +27,6 @@ public class Post {
2827
@Lob
2928
private String content;
3029

31-
@NotNull
32-
@Temporal(TemporalType.TIMESTAMP)
33-
@Column(name = "posted_at")
34-
private Date postedAt = new Date();
35-
36-
@NotNull
37-
@Temporal(TemporalType.TIMESTAMP)
38-
@Column(name = "last_updated_at")
39-
private Date lastUpdatedAt = new Date();
40-
41-
@OneToMany(cascade = CascadeType.ALL,
42-
fetch = FetchType.LAZY,
43-
mappedBy = "post")
44-
private Set<Comment> comments = new HashSet<>();
45-
46-
public Post() {
47-
48-
}
49-
50-
public Post(String title, String description, String content) {
51-
this.title = title;
52-
this.description = description;
53-
this.content = content;
54-
}
55-
5630
public Long getId() {
5731
return id;
5832
}
@@ -84,28 +58,4 @@ public String getContent() {
8458
public void setContent(String content) {
8559
this.content = content;
8660
}
87-
88-
public Date getPostedAt() {
89-
return postedAt;
90-
}
91-
92-
public void setPostedAt(Date postedAt) {
93-
this.postedAt = postedAt;
94-
}
95-
96-
public Date getLastUpdatedAt() {
97-
return lastUpdatedAt;
98-
}
99-
100-
public void setLastUpdatedAt(Date lastUpdatedAt) {
101-
this.lastUpdatedAt = lastUpdatedAt;
102-
}
103-
104-
public Set<Comment> getComments() {
105-
return comments;
106-
}
107-
108-
public void setComments(Set<Comment> comments) {
109-
this.comments = comments;
110-
}
11161
}
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.example.jpa.repository;
22

33
import com.example.jpa.model.Comment;
4+
import org.springframework.data.domain.Page;
5+
import org.springframework.data.domain.Pageable;
46
import org.springframework.data.jpa.repository.JpaRepository;
57
import org.springframework.stereotype.Repository;
68

@@ -9,5 +11,5 @@
911
*/
1012
@Repository
1113
public interface CommentRepository extends JpaRepository<Comment, Long> {
12-
14+
Page<Comment> findByPostId(Long postId, Pageable pageable);
1315
}

0 commit comments

Comments
 (0)