Quellcode durchsuchen

crud for posts and users

nafis nibir vor 6 Jahren
Ursprung
Commit
684d4d6ec2

+ 28
- 8
src/main/java/com/ziplinegreen/vault/Controller/PostController.java Datei anzeigen

10
 import org.springframework.beans.factory.annotation.Autowired;
10
 import org.springframework.beans.factory.annotation.Autowired;
11
 import org.springframework.data.domain.Page;
11
 import org.springframework.data.domain.Page;
12
 import org.springframework.data.domain.Pageable;
12
 import org.springframework.data.domain.Pageable;
13
+import org.springframework.data.repository.query.Param;
13
 import org.springframework.http.HttpStatus;
14
 import org.springframework.http.HttpStatus;
14
 import org.springframework.http.ResponseEntity;
15
 import org.springframework.http.ResponseEntity;
15
 import org.springframework.web.bind.annotation.*;
16
 import org.springframework.web.bind.annotation.*;
17
 import javax.validation.Valid;
18
 import javax.validation.Valid;
18
 import java.util.Set;
19
 import java.util.Set;
19
 
20
 
20
-
21
+@RestController
21
 public class PostController {
22
 public class PostController {
22
 
23
 
23
     private PostService postService;
24
     private PostService postService;
28
         this.postService = postService;
29
         this.postService = postService;
29
     }
30
     }
30
 
31
 
31
-    @PostMapping("/posts/{userId}")
32
-    public ResponseEntity createPost(@PathVariable Long userId, @RequestBody Post post) {
33
-        userController.updatePosts(userId,post);
34
-        return new ResponseEntity(HttpStatus.OK);
32
+    @PostMapping("/{userId}/posts")
33
+    public ResponseEntity<Post> createPost(@PathVariable Long userId, @RequestBody String message){
34
+        return postService.createPost(userId,message);
35
+    }
35
 
36
 
37
+    @GetMapping("/{userId}/posts")
38
+    public ResponseEntity<Iterable<Post>> getAllPostsByUserId(@PathVariable Long userId) {
39
+        return postService.findAllByUserId(userId);
36
     }
40
     }
37
 
41
 
42
+    @GetMapping("/{userId}/posts/{postId}")
43
+    public ResponseEntity<Post> getPostById(@PathVariable Long userId, @PathVariable Long postId){
44
+        return postService.getPostById(postId);
45
+    }
38
 
46
 
39
-    @GetMapping("/posts/{userId}")
40
-    public ResponseEntity<Iterable<Post>> getAllPostsByUserId(@PathVariable Long userId) {
41
-        return postService.findByUserId(userId);
47
+    @PutMapping("/{userId}/posts/{postId}")
48
+    public ResponseEntity<Post> updatePost(@PathVariable Long userId, @PathVariable Long postId, @RequestBody String message){
49
+        return postService.updatePost(postId, message);
50
+    }
51
+
52
+    @DeleteMapping("/{userId}/posts/{postId}")
53
+    public ResponseEntity deletePost(@PathVariable Long userId, @PathVariable Long postId){
54
+        return postService.deletePost(postId);
42
     }
55
     }
43
 
56
 
44
 //    @PutMapping("/users/{userId/posts")
57
 //    @PutMapping("/users/{userId/posts")
75
 //        }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found"));
88
 //        }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found"));
76
 //    }
89
 //    }
77
 }
90
 }
91
+
92
+
93
+//    @PutMapping("/{userId}/posts")
94
+//    public ResponseEntity<?> addPost(@PathVariable Long userId, @RequestBody String message){
95
+//        Post post = new Post(message, userId);
96
+//        return userService.addpost(userId, post);
97
+//    }

+ 3
- 11
src/main/java/com/ziplinegreen/vault/Controller/UserController.java Datei anzeigen

37
     }
37
     }
38
 
38
 
39
     @PutMapping("/users/{userId}")
39
     @PutMapping("/users/{userId}")
40
-    public ResponseEntity<User> updateUsername(@PathVariable Long userId, @Valid @RequestBody User userRequest) {
41
-        return new ResponseEntity<>(userService.updateUsername(userId,userRequest), HttpStatus.OK);
40
+    public ResponseEntity<User> updateUsername(@PathVariable Long userId, @RequestBody String newUsername) {
41
+        return userService.updateUsername(userId,newUsername);
42
     }
42
     }
43
 
43
 
44
-
45
     @DeleteMapping("/users/{userId}")
44
     @DeleteMapping("/users/{userId}")
46
-    public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
45
+    public ResponseEntity deleteUser(@PathVariable Long userId) {
47
         return userService.deleteUser(userId);
46
         return userService.deleteUser(userId);
48
     }
47
     }
49
-
50
-    @PutMapping("/users/{userId}/updatepost")
51
-    public ResponseEntity<?> updatePosts(@PathVariable Long userId, @RequestBody Post post){
52
-        return userService.updatePosts(userId, post);
53
-    }
54
-
55
-
56
 }
48
 }

+ 11
- 20
src/main/java/com/ziplinegreen/vault/Model/Post.java Datei anzeigen

2
 
2
 
3
 
3
 
4
 import com.fasterxml.jackson.annotation.JsonIgnore;
4
 import com.fasterxml.jackson.annotation.JsonIgnore;
5
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
5
 import org.hibernate.annotations.OnDelete;
6
 import org.hibernate.annotations.OnDelete;
6
 import org.hibernate.annotations.OnDeleteAction;
7
 import org.hibernate.annotations.OnDeleteAction;
7
 
8
 
8
 import javax.persistence.*;
9
 import javax.persistence.*;
9
 import javax.validation.constraints.NotNull;
10
 import javax.validation.constraints.NotNull;
10
 
11
 
11
-@Entity
12
-@Table(name = "post")
12
+@Entity @Table(name = "post")
13
+@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
13
 public class Post extends AuditModel{
14
 public class Post extends AuditModel{
14
 
15
 
15
-    @Id
16
-    @GeneratedValue(strategy = GenerationType.IDENTITY)
16
+    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
17
     private Long Id;
17
     private Long Id;
18
 
18
 
19
     @NotNull
19
     @NotNull
20
-    @Lob
21
     private String message;
20
     private String message;
21
+
22
+    @NotNull
22
     private Long userId;
23
     private Long userId;
23
-//    @OnDelete(action = OnDeleteAction.CASCADE)
24
-//    @JsonIgnore
25
 
24
 
26
-    public Post(){
27
-    }
28
-    public Post(@NotNull String message, Long userId) {
25
+    public Post(){}
26
+    public Post(@NotNull String message, @NotNull Long userId) {
29
         this.message = message;
27
         this.message = message;
30
         this.userId = userId;
28
         this.userId = userId;
31
     }
29
     }
32
 
30
 
33
-    public Long getId() {
34
-        return Id;
35
-    }
36
-
31
+    public Long getId() { return Id; }
37
 
32
 
38
     public String getMessage() {
33
     public String getMessage() {
39
         return message;
34
         return message;
40
     }
35
     }
41
 
36
 
42
-    public void setMessage(String message) {
43
-        this.message = message;
44
-    }
37
+    public void setMessage(String message) { this.message = message; }
45
 
38
 
46
-    public Long getUserId() {
47
-        return userId;
48
-    }
39
+    public Long getUserId() { return userId; }
49
 
40
 
50
 }
41
 }

+ 24
- 41
src/main/java/com/ziplinegreen/vault/Model/User.java Datei anzeigen

19
     private String username;
19
     private String username;
20
     private String email;
20
     private String email;
21
     private String password;
21
     private String password;
22
-    @OneToMany(fetch = FetchType.LAZY,
23
-            cascade= {
24
-                CascadeType.PERSIST,
25
-                CascadeType.MERGE
26
-            })
27
-    @JoinTable(name = "user_posts",
28
-            joinColumns = {@JoinColumn(name = "user_id")})
29
-    private List<Post> posts = new ArrayList<>();
30
-
31
-    public List<Post> getPosts() {
32
-        if(posts.size()==0){
33
-            posts = new ArrayList<>();
34
-            return posts;
35
-        }
36
-        return posts;
37
-    }
22
+//    @OneToMany(fetch = FetchType.LAZY,
23
+//            cascade= {
24
+//                CascadeType.PERSIST,
25
+//                CascadeType.MERGE
26
+//            })
27
+//    @JoinTable(name = "user_posts",
28
+//            joinColumns = {@JoinColumn(name = "user_id")})
29
+//    private List<Post> posts = new ArrayList<>();
38
 
30
 
39
     public User(){}
31
     public User(){}
40
     public User(@NotNull String username, String email, String password) {
32
     public User(@NotNull String username, String email, String password) {
43
         this.password = password;
35
         this.password = password;
44
     }
36
     }
45
 
37
 
46
-    public void setPosts(List<Post> posts) {
47
-        this.posts = posts;
48
-    }
38
+    public Long getId() { return id; }
49
 
39
 
50
-    public Long getId() {
51
-        return id;
52
-    }
40
+    public String getEmail() { return email;}
53
 
41
 
54
-    public String getEmail() {
55
-        return email;
56
-    }
57
-
58
-    public void setEmail(String email) {
59
-        this.email = email;
60
-    }
42
+    public void setEmail(String email) { this.email = email; }
61
 
43
 
62
-    public String getPassword() {
63
-        return password;
64
-    }
44
+    public String getPassword() { return password; }
65
 
45
 
66
-    public void setPassword(String password) {
67
-        this.password = password;
68
-    }
46
+    public void setPassword(String password) { this.password = password; }
69
 
47
 
70
-    public String getUsername() {
71
-        return username;
72
-    }
48
+    public String getUsername() { return username; }
73
 
49
 
74
-    public void setUsername(String username) {
75
-        this.username = username;
76
-    }
50
+    public void setUsername(String username) { this.username = username; }
77
 
51
 
52
+//    public List<Post> getPosts() {
53
+//        if(posts.size()==0){
54
+//            posts = new ArrayList<>();
55
+//            return posts;
56
+//        }
57
+//        return posts;
58
+//    }
59
+//
60
+//    public void setPosts(List<Post> posts) { this.posts = posts; }
78
 }
61
 }

+ 3
- 2
src/main/java/com/ziplinegreen/vault/Repository/PostRepository.java Datei anzeigen

7
 import org.springframework.data.jpa.repository.Query;
7
 import org.springframework.data.jpa.repository.Query;
8
 import org.springframework.data.repository.query.Param;
8
 import org.springframework.data.repository.query.Param;
9
 import org.springframework.data.rest.core.annotation.RepositoryRestResource;
9
 import org.springframework.data.rest.core.annotation.RepositoryRestResource;
10
+import org.springframework.http.ResponseEntity;
10
 import org.springframework.stereotype.Repository;
11
 import org.springframework.stereotype.Repository;
11
 
12
 
12
 @RepositoryRestResource
13
 @RepositoryRestResource
13
 public interface PostRepository extends JpaRepository<Post,Long> {
14
 public interface PostRepository extends JpaRepository<Post,Long> {
14
 
15
 
15
-    //@Query("select postcontent,timestamp from Post where user_id = :userId")
16
-    Iterable<Post> findByUserId(Long userId);
16
+    Iterable<Post> findAllByUserId(Long userId);
17
+
17
 }
18
 }

+ 34
- 8
src/main/java/com/ziplinegreen/vault/Service/PostService.java Datei anzeigen

1
 package com.ziplinegreen.vault.Service;
1
 package com.ziplinegreen.vault.Service;
2
 
2
 
3
 
3
 
4
+import com.ziplinegreen.vault.Controller.UserController;
4
 import com.ziplinegreen.vault.Model.Post;
5
 import com.ziplinegreen.vault.Model.Post;
6
+import com.ziplinegreen.vault.Model.User;
5
 import com.ziplinegreen.vault.Repository.PostRepository;
7
 import com.ziplinegreen.vault.Repository.PostRepository;
6
 import org.springframework.beans.factory.annotation.Autowired;
8
 import org.springframework.beans.factory.annotation.Autowired;
7
 import org.springframework.http.HttpStatus;
9
 import org.springframework.http.HttpStatus;
8
 import org.springframework.http.ResponseEntity;
10
 import org.springframework.http.ResponseEntity;
9
 import org.springframework.stereotype.Service;
11
 import org.springframework.stereotype.Service;
10
 
12
 
13
+import java.util.List;
14
+
11
 @Service
15
 @Service
12
 public class PostService {
16
 public class PostService {
13
 
17
 
14
     private PostRepository postRepository;
18
     private PostRepository postRepository;
19
+    private UserController userController;
15
 
20
 
16
     @Autowired
21
     @Autowired
17
     public PostService(PostRepository postRepository) {
22
     public PostService(PostRepository postRepository) {
18
         this.postRepository = postRepository;
23
         this.postRepository = postRepository;
19
     }
24
     }
20
 
25
 
21
-    public ResponseEntity<Post> createPost(Post post){
26
+    public ResponseEntity<Post> createPost(Long userId, String message){
27
+        Post post = new Post(message,userId);
22
         return new ResponseEntity<>(postRepository.save(post), HttpStatus.CREATED);
28
         return new ResponseEntity<>(postRepository.save(post), HttpStatus.CREATED);
23
     }
29
     }
24
 
30
 
25
-    public ResponseEntity<Post> deletePost(Long id){
26
-        Post post = postRepository.getOne(id);
31
+    public ResponseEntity<Iterable<Post>> findAllByUserId(Long userId) {
32
+        return new ResponseEntity<>(postRepository.findAllByUserId(userId), HttpStatus.OK);
33
+    }
34
+
35
+    public ResponseEntity<Post> updatePost(Long postId, String message) {
36
+        Post post = findById(postId);
37
+        post.setMessage(message);
38
+        return new ResponseEntity<>(postRepository.save(post), HttpStatus.OK);
39
+    }
40
+
41
+
42
+    private Post findById(Long postId) {
43
+        return postRepository.findById(postId).get();
44
+    }
45
+
46
+    public ResponseEntity<Post> getPostById(Long postId) {
47
+        Post post = postRepository.getOne(postId);
48
+        return new ResponseEntity<>(post, HttpStatus.OK);
49
+    }
50
+
51
+    public ResponseEntity<Post> deletePost(Long postId){
52
+        Post post = postRepository.getOne(postId);
27
         postRepository.delete(post);
53
         postRepository.delete(post);
28
         return new ResponseEntity<>(HttpStatus.OK);
54
         return new ResponseEntity<>(HttpStatus.OK);
29
     }
55
     }
30
 
56
 
31
-    public ResponseEntity<Iterable<Post>> findByUserId(Long userId) {
32
-        return new ResponseEntity<>(postRepository.findByUserId(userId), HttpStatus.OK);
33
-    }
34
 
57
 
35
-//    public ResponseEntity<Post> updatePost(Long userId, Post post) {
36
-//
58
+//    public ResponseEntity<User> addpost(Long userId, Post post) {
59
+//        User user = findUserById(userId).getBody();
60
+//        List<Post> posts = user.getPosts();
61
+//        posts.add(post);
62
+//        return new ResponseEntity<>(userRepository.save(user), HttpStatus.OK);
37
 //    }
63
 //    }
38
 }
64
 }
39
 
65
 

+ 12
- 14
src/main/java/com/ziplinegreen/vault/Service/UserService.java Datei anzeigen

33
         return new ResponseEntity<>(userRepository.findById(id).get(),HttpStatus.OK);
33
         return new ResponseEntity<>(userRepository.findById(id).get(),HttpStatus.OK);
34
     }
34
     }
35
 
35
 
36
-    public User updateUsername(Long id, User updatedUser){return userRepository.findById(id).map(user -> {
37
-        user.setUsername(updatedUser.getUsername());
38
-        return userRepository.save(user);
39
-    }).orElseThrow(() -> new ResourceNotFoundException("UserId " + id + " not found"));
36
+    public ResponseEntity<User> updateUsername(Long id, String newUsername) {
37
+        User user = findUserById(id).getBody();
38
+        user.setUsername(newUsername);
39
+        return new ResponseEntity<>(userRepository.save(user),HttpStatus.OK);
40
     }
40
     }
41
 
41
 
42
-    public ResponseEntity deleteUser(Long id){return userRepository.findById(id).map(user -> {
43
-        userRepository.delete(user);
42
+    public ResponseEntity deleteUser(Long id){
43
+        userRepository.delete(userRepository.findById(id).get());
44
         return new ResponseEntity(HttpStatus.OK);
44
         return new ResponseEntity(HttpStatus.OK);
45
-    }).orElseThrow(() -> new ResourceNotFoundException("UserId " + id + " not found"));
46
-
47
     }
45
     }
48
 
46
 
49
-    public ResponseEntity<User> updatePosts(Long userId, Post post) {
50
-        User user = findUserById(userId).getBody();
51
-        List<Post> posts = user.getPosts();
52
-        posts.add(post);
53
-        return new ResponseEntity<>(userRepository.save(user), HttpStatus.OK);
54
-    }
47
+
48
+
49
+
50
+
51
+
52
+
55
 }
53
 }
56
 
54
 
57
 
55
 

+ 3
- 0
src/main/resources/application.properties Datei anzeigen

8
 spring.datasource.password=
8
 spring.datasource.password=
9
 spring.datasource.driver-class-name=org.h2.Driver
9
 spring.datasource.driver-class-name=org.h2.Driver
10
 
10
 
11
+#logging.level.org.springframework.web=DEBUG
12
+
13
+
11
 
14
 
12
 #spring.datasource.url=jdbc:mysql://localhost:3306/zipLine?useSSL=false
15
 #spring.datasource.url=jdbc:mysql://localhost:3306/zipLine?useSSL=false
13
 #spring.datasource.username=root
16
 #spring.datasource.username=root