nafis nibir преди 6 години
родител
ревизия
eb9fac0dfc

+ 10
- 10
pom.xml Целия файл

@@ -34,21 +34,21 @@
34 34
             <artifactId>spring-boot-starter-web</artifactId>
35 35
         </dependency>
36 36
 
37
-        <dependency>
38
-            <groupId>mysql</groupId>
39
-            <artifactId>mysql-connector-java</artifactId>
40
-            <scope>runtime</scope>
41
-        </dependency>
37
+        <!--<dependency>-->
38
+            <!--<groupId>mysql</groupId>-->
39
+            <!--<artifactId>mysql-connector-java</artifactId>-->
40
+            <!--<scope>runtime</scope>-->
41
+        <!--</dependency>-->
42 42
 
43 43
         <dependency>
44 44
             <groupId>org.springframework.boot</groupId>
45 45
             <artifactId>spring-boot-starter-data-rest</artifactId>
46 46
         </dependency>
47
-        <!--<dependency>-->
48
-            <!--<groupId>com.h2database</groupId>-->
49
-            <!--<artifactId>h2</artifactId>-->
50
-            <!--<scope>runtime</scope>-->
51
-        <!--</dependency>-->
47
+        <dependency>
48
+            <groupId>com.h2database</groupId>
49
+            <artifactId>h2</artifactId>
50
+            <scope>runtime</scope>
51
+        </dependency>
52 52
         <dependency>
53 53
             <groupId>org.springframework.boot</groupId>
54 54
             <artifactId>spring-boot-starter-test</artifactId>

+ 49
- 37
src/main/java/com/ziplinegreen/vault/Controller/PostController.java Целия файл

@@ -2,64 +2,76 @@ package com.ziplinegreen.vault.Controller;
2 2
 
3 3
 import com.ziplinegreen.vault.Exception.ResourceNotFoundException;
4 4
 import com.ziplinegreen.vault.Model.Post;
5
+import com.ziplinegreen.vault.Model.User;
5 6
 import com.ziplinegreen.vault.Repository.PostRepository;
6 7
 import com.ziplinegreen.vault.Repository.UserRepository;
8
+import com.ziplinegreen.vault.Service.PostService;
9
+import com.ziplinegreen.vault.Service.UserService;
7 10
 import org.springframework.beans.factory.annotation.Autowired;
8 11
 import org.springframework.data.domain.Page;
9 12
 import org.springframework.data.domain.Pageable;
13
+import org.springframework.http.HttpStatus;
10 14
 import org.springframework.http.ResponseEntity;
11 15
 import org.springframework.web.bind.annotation.*;
12 16
 
13 17
 import javax.validation.Valid;
18
+import java.util.Set;
14 19
 
15 20
 
16 21
 public class PostController {
17 22
 
18
-    @Autowired
19
-    private PostRepository postRepository;
23
+    private PostService postService;
24
+    private UserController userController;
20 25
 
21 26
     @Autowired
22
-    private UserRepository userRepository;
23
-
24
-    @GetMapping("/users/{userId}/posts")
25
-    public Page<Post> getAllPostsByUserId(@PathVariable(value = "userId") Long userId,
26
-                                             Pageable pageable) {
27
-        return postRepository.findByUserId(userId, pageable);
27
+    public PostController(PostService postService) {
28
+        this.postService = postService;
28 29
     }
29 30
 
30
-    @PostMapping("/users/{userId}/posts")
31
-    public Post createPost(@PathVariable (value = "userId") Long userId,
32
-                                 @Valid @RequestBody Post post) {
33
-        return userRepository.findById(userId).map(user -> {
34
-            post.setUser(user);
35
-            return postRepository.save(post);
36
-        }).orElseThrow(() -> new ResourceNotFoundException("UserId " + userId + " not found"));
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);
35
+
37 36
     }
38 37
 
39
-    @PutMapping("/users/{userId}/posts/{postId}")
40
-    public Post updateComment(@PathVariable (value = "userId") Long userId,
41
-                                 @PathVariable (value = "postId") Long postId,
42
-                                 @Valid @RequestBody Post postRequest) {
43
-        if(!userRepository.existsById(userId)) {
44
-            throw new ResourceNotFoundException("UserId " + userId + " not found");
45
-        }
46 38
 
47
-        return postRepository.findById(postId).map(post -> {
48
-            post.setMessage(postRequest.getMessage());
49
-            return postRepository.save(post);
50
-        }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + "not found"));
39
+    @GetMapping("/posts/{userId}")
40
+    public ResponseEntity<Iterable<Post>> getAllPostsByUserId(@PathVariable Long userId) {
41
+        return postService.findByUserId(userId);
51 42
     }
52 43
 
53
-    @DeleteMapping("/posts/{postId}/comments/{commentId}")
54
-    public ResponseEntity<?> deleteComment(@PathVariable (value = "userId") Long userId,
55
-                                           @PathVariable (value = "postId") Long postId) {
56
-        if(!userRepository.existsById(userId)) {
57
-            throw new ResourceNotFoundException("UserId " + userId + " not found");
58
-        }
44
+//    @PutMapping("/users/{userId/posts")
45
+//    public ResponseEntity<Post> updatePost(@PathVariable Long userId, @RequestBody Post post){
46
+//        return postService.updatePost(userId, post);
47
+//    }
59 48
 
60
-        return postRepository.findById(postId).map(post -> {
61
-            postRepository.delete(post);
62
-            return ResponseEntity.ok().build();
63
-        }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found"));
64
-    }
49
+
50
+
51
+//    @PutMapping("/users/{userId}/posts/{postId}")
52
+//    public Post updateComment(@PathVariable (value = "userId") Long userId,
53
+//                                 @PathVariable (value = "postId") Long postId,
54
+//                                 @Valid @RequestBody Post postRequest) {
55
+//        if(!userRepository.existsById(userId)) {
56
+//            throw new ResourceNotFoundException("UserId " + userId + " not found");
57
+//        }
58
+//
59
+//        return postRepository.findById(postId).map(post -> {
60
+//            post.setMessage(postRequest.getMessage());
61
+//            return postRepository.save(post);
62
+//        }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + "not found"));
63
+//    }
64
+//
65
+//    @DeleteMapping("/posts/{postId}/comments/{commentId}")
66
+//    public ResponseEntity<?> deleteComment(@PathVariable (value = "userId") Long userId,
67
+//                                           @PathVariable (value = "postId") Long postId) {
68
+//        if(!userRepository.existsById(userId)) {
69
+//            throw new ResourceNotFoundException("UserId " + userId + " not found");
70
+//        }
71
+//
72
+//        return postRepository.findById(postId).map(post -> {
73
+//            postRepository.delete(post);
74
+//            return ResponseEntity.ok().build();
75
+//        }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found"));
76
+//    }
65 77
 }

+ 25
- 16
src/main/java/com/ziplinegreen/vault/Controller/UserController.java Целия файл

@@ -1,47 +1,56 @@
1 1
 package com.ziplinegreen.vault.Controller;
2 2
 
3 3
 import com.ziplinegreen.vault.Exception.ResourceNotFoundException;
4
+import com.ziplinegreen.vault.Model.Post;
4 5
 import com.ziplinegreen.vault.Model.User;
5 6
 import com.ziplinegreen.vault.Repository.UserRepository;
6 7
 import com.ziplinegreen.vault.Service.UserService;
7 8
 import org.springframework.beans.factory.annotation.Autowired;
8 9
 import org.springframework.data.domain.Page;
9 10
 import org.springframework.data.domain.Pageable;
11
+import org.springframework.http.HttpStatus;
10 12
 import org.springframework.http.ResponseEntity;
11 13
 import org.springframework.web.bind.annotation.*;
12 14
 
13 15
 import javax.validation.Valid;
16
+import java.util.List;
17
+import java.util.Set;
14 18
 
15 19
 @RestController
16 20
 public class UserController {
17 21
 
18
-    @Autowired
19 22
     private UserService userService;
20 23
 
21
-    @GetMapping("/users")
22
-    public Page<User> getAllPosts(Pageable pageable) {
23
-        return userRepository.findAll(pageable);
24
+    @Autowired
25
+    public UserController(UserService userService) {
26
+        this.userService = userService;
24 27
     }
25 28
 
26 29
     @PostMapping("/users")
27
-    public User createPost(@Valid @RequestBody User user) {
28
-        return userRepository.save(user);
30
+    public ResponseEntity<User> createUser(@RequestBody User user) {
31
+        return userService.createUser(user);
32
+    }
33
+
34
+    @GetMapping("/users/{userId}")
35
+    public ResponseEntity<User> getUserById(@PathVariable Long userId) {
36
+        return userService.findUserById(userId);
29 37
     }
30 38
 
31 39
     @PutMapping("/users/{userId}")
32
-    public User updatePost(@PathVariable Long userId, @Valid @RequestBody User userRequest) {
33
-        return userRepository.findById(userId).map(user -> {
34
-            user.setUsername(userRequest.getUsername());
35
-            return userRepository.save(user);
36
-        }).orElseThrow(() -> new ResourceNotFoundException("UserId " + userId + " not found"));
40
+    public ResponseEntity<User> updateUsername(@PathVariable Long userId, @Valid @RequestBody User userRequest) {
41
+        return new ResponseEntity<>(userService.updateUsername(userId,userRequest), HttpStatus.OK);
37 42
     }
38 43
 
39 44
 
40 45
     @DeleteMapping("/users/{userId}")
41
-    public ResponseEntity<?> deletePost(@PathVariable Long userId) {
42
-        return userRepository.findById(userId).map(user -> {
43
-            userRepository.delete(user);
44
-            return ResponseEntity.ok().build();
45
-        }).orElseThrow(() -> new ResourceNotFoundException("UserId " + userId + " not found"));
46
+    public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
47
+        return userService.deleteUser(userId);
46 48
     }
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
+
47 56
 }

+ 12
- 14
src/main/java/com/ziplinegreen/vault/Model/Post.java Целия файл

@@ -13,26 +13,27 @@ import javax.validation.constraints.NotNull;
13 13
 public class Post extends AuditModel{
14 14
 
15 15
     @Id
16
-    @GeneratedValue
16
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
17 17
     private Long Id;
18 18
 
19 19
     @NotNull
20 20
     @Lob
21 21
     private String message;
22
+    private Long userId;
23
+//    @OnDelete(action = OnDeleteAction.CASCADE)
24
+//    @JsonIgnore
22 25
 
23
-    @ManyToOne(fetch = FetchType.LAZY, optional = false)
24
-    @JoinColumn(name = "user_id", nullable = false)
25
-    @OnDelete(action = OnDeleteAction.CASCADE)
26
-    @JsonIgnore
27
-    private User user;
26
+    public Post(){
27
+    }
28
+    public Post(@NotNull String message, Long userId) {
29
+        this.message = message;
30
+        this.userId = userId;
31
+    }
28 32
 
29 33
     public Long getId() {
30 34
         return Id;
31 35
     }
32 36
 
33
-    public void setId(Long id) {
34
-        Id = id;
35
-    }
36 37
 
37 38
     public String getMessage() {
38 39
         return message;
@@ -42,11 +43,8 @@ public class Post extends AuditModel{
42 43
         this.message = message;
43 44
     }
44 45
 
45
-    public User getUser() {
46
-        return user;
46
+    public Long getUserId() {
47
+        return userId;
47 48
     }
48 49
 
49
-    public void setUser(User user) {
50
-        this.user = user;
51
-    }
52 50
 }

+ 36
- 4
src/main/java/com/ziplinegreen/vault/Model/User.java Целия файл

@@ -1,20 +1,51 @@
1 1
 package com.ziplinegreen.vault.Model;
2 2
 
3
+import com.fasterxml.jackson.annotation.JsonIgnore;
4
+import org.hibernate.annotations.OnDelete;
5
+import org.hibernate.annotations.OnDeleteAction;
6
+
3 7
 import javax.persistence.*;
4 8
 import javax.validation.constraints.NotNull;
9
+import java.util.ArrayList;
10
+import java.util.List;
5 11
 
6 12
 @Entity
7 13
 @Table(name = "user")
8 14
 public class User extends AuditModel{
9 15
     @Id
10
-    @GeneratedValue
16
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
11 17
     private Long id;
12
-
13
-//    @NotNull
14
-    @Column(name ="USER_USERNAME")
18
+    @NotNull
15 19
     private String username;
16 20
     private String email;
17 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
+    }
38
+
39
+    public User(){}
40
+    public User(@NotNull String username, String email, String password) {
41
+        this.username = username;
42
+        this.email = email;
43
+        this.password = password;
44
+    }
45
+
46
+    public void setPosts(List<Post> posts) {
47
+        this.posts = posts;
48
+    }
18 49
 
19 50
     public Long getId() {
20 51
         return id;
@@ -43,4 +74,5 @@ public class User extends AuditModel{
43 74
     public void setUsername(String username) {
44 75
         this.username = username;
45 76
     }
77
+
46 78
 }

+ 2
- 2
src/main/java/com/ziplinegreen/vault/Repository/PostRepository.java Целия файл

@@ -12,6 +12,6 @@ import org.springframework.stereotype.Repository;
12 12
 @RepositoryRestResource
13 13
 public interface PostRepository extends JpaRepository<Post,Long> {
14 14
 
15
-    @Query("select postcontent,timestamp from Post where user_id = :userId")
16
-    Page<Post> findByUserId(@Param("userId")Long userId, Pageable pageable);
15
+    //@Query("select postcontent,timestamp from Post where user_id = :userId")
16
+    Iterable<Post> findByUserId(Long userId);
17 17
 }

+ 8
- 0
src/main/java/com/ziplinegreen/vault/Service/PostService.java Целия файл

@@ -27,5 +27,13 @@ public class PostService {
27 27
         postRepository.delete(post);
28 28
         return new ResponseEntity<>(HttpStatus.OK);
29 29
     }
30
+
31
+    public ResponseEntity<Iterable<Post>> findByUserId(Long userId) {
32
+        return new ResponseEntity<>(postRepository.findByUserId(userId), HttpStatus.OK);
33
+    }
34
+
35
+//    public ResponseEntity<Post> updatePost(Long userId, Post post) {
36
+//
37
+//    }
30 38
 }
31 39
 

+ 27
- 11
src/main/java/com/ziplinegreen/vault/Service/UserService.java Целия файл

@@ -1,6 +1,7 @@
1 1
 package com.ziplinegreen.vault.Service;
2 2
 
3 3
 import com.ziplinegreen.vault.Controller.PostController;
4
+import com.ziplinegreen.vault.Exception.ResourceNotFoundException;
4 5
 import com.ziplinegreen.vault.Model.Post;
5 6
 import com.ziplinegreen.vault.Model.User;
6 7
 import com.ziplinegreen.vault.Repository.UserRepository;
@@ -8,34 +9,49 @@ import org.springframework.beans.factory.annotation.Autowired;
8 9
 import org.springframework.http.HttpStatus;
9 10
 import org.springframework.http.ResponseEntity;
10 11
 import org.springframework.stereotype.Service;
12
+import org.springframework.web.server.ResponseStatusException;
11 13
 
12 14
 import javax.xml.ws.Response;
15
+import java.util.List;
13 16
 
14 17
 @Service
15 18
 public class UserService {
16 19
 
17 20
     private UserRepository userRepository;
18
-    private PostController postController;
21
+    //private PostController postController;
19 22
 
20 23
     @Autowired
21
-    public UserService(UserRepository userRepository, PostController postController) {
24
+    public UserService(UserRepository userRepository) {
22 25
         this.userRepository = userRepository;
23
-        this.postController = postController;
24 26
     }
25 27
 
26 28
     public ResponseEntity<User> createUser(User user){
27 29
         return new ResponseEntity<>(userRepository.save(user), HttpStatus.CREATED);
28 30
     }
29 31
 
30
-    public ResponseEntity<User> deleteUser(Long id){
31
-        User user = userRepository.getOne(id);
32
-        userRepository.delete(user);
33
-        return new ResponseEntity<>(HttpStatus.OK);
32
+    public ResponseEntity<User> findUserById(Long id){
33
+        return new ResponseEntity<>(userRepository.findById(id).get(),HttpStatus.OK);
34 34
     }
35 35
 
36
-//    public ResponseEntity<User> updatePost(Long userId){
37
-//        User user = userRepository.getOne(userId);
38
-//
39
-//    }
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"));
40
+    }
40 41
 
42
+    public ResponseEntity deleteUser(Long id){return userRepository.findById(id).map(user -> {
43
+        userRepository.delete(user);
44
+        return new ResponseEntity(HttpStatus.OK);
45
+    }).orElseThrow(() -> new ResourceNotFoundException("UserId " + id + " not found"));
46
+
47
+    }
48
+
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
+    }
41 55
 }
56
+
57
+

+ 20
- 20
src/main/resources/application.properties Целия файл

@@ -1,23 +1,23 @@
1
-## H2
2
-#spring.h2.console.enabled=true
3
-#spring.h2.console.path=/h2
4
-#
5
-## Datasource
6
-#spring.datasource.url=jdbc:h2:file:~/test
7
-#spring.datasource.username=sa
8
-#spring.datasource.password=
9
-#spring.datasource.driver-class-name=org.h2.Driver
10
-
11
-
12
-spring.datasource.url=jdbc:mysql://localhost:3306/zipLine?useSSL=false
13
-spring.datasource.username=root
14
-spring.datasource.password=Calcifer1650
1
+# H2
2
+spring.h2.console.enabled=true
3
+spring.h2.console.path=/h2
15 4
 
16
-# The SQL dialect makes Hibernate generate better SQL for the chosen database
17
-spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
5
+# Datasource
6
+spring.datasource.url=jdbc:h2:file:~/test
7
+spring.datasource.username=sa
8
+spring.datasource.password=
9
+spring.datasource.driver-class-name=org.h2.Driver
18 10
 
19
-# Hibernate ddl auto (create, create-drop, validate, update)
20
-spring.jpa.hibernate.ddl-auto = update
21 11
 
22
-logging.level.org.hibernate.SQL=DEBUG
23
-logging.level.org.hibernate.type=TRACE
12
+#spring.datasource.url=jdbc:mysql://localhost:3306/zipLine?useSSL=false
13
+#spring.datasource.username=root
14
+#spring.datasource.password=Calcifer1650
15
+#
16
+## The SQL dialect makes Hibernate generate better SQL for the chosen database
17
+#spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
18
+#
19
+## Hibernate ddl auto (create, create-drop, validate, update)
20
+#spring.jpa.hibernate.ddl-auto = update
21
+#
22
+#logging.level.org.hibernate.SQL=DEBUG
23
+#logging.level.org.hibernate.type=TRACE