Browse Source

add crud controller

Nhu Nguyen 6 years ago
parent
commit
56a4ae753a

+ 2
- 0
src/main/java/com/example/demo/DemoApplication.java View File

2
 
2
 
3
 import org.springframework.boot.SpringApplication;
3
 import org.springframework.boot.SpringApplication;
4
 import org.springframework.boot.autoconfigure.SpringBootApplication;
4
 import org.springframework.boot.autoconfigure.SpringBootApplication;
5
+import org.springframework.context.annotation.Bean;
6
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
5
 
7
 
6
 @SpringBootApplication
8
 @SpringBootApplication
7
 public class DemoApplication {
9
 public class DemoApplication {

+ 24
- 0
src/main/java/com/example/demo/user/UserController.java View File

1
+package com.example.demo.user;
2
+
3
+import org.springframework.beans.factory.annotation.Autowired;
4
+import org.springframework.web.bind.annotation.RequestMapping;
5
+import org.springframework.web.bind.annotation.RequestParam;
6
+import org.springframework.web.bind.annotation.RestController;
7
+
8
+import java.util.List;
9
+
10
+@RestController
11
+public class UserController {
12
+    @Autowired
13
+    private UserRepository userRepository;
14
+
15
+    @RequestMapping(path="/users/search")
16
+    public User getUserByName(@RequestParam("name") String name) {
17
+        return userRepository.findByName(name);
18
+    }
19
+
20
+    @RequestMapping(path="/users/active")
21
+    public List<User> getActiveUser() {
22
+        return userRepository.findAllByActive(true);
23
+    }
24
+}

+ 4
- 0
src/main/java/com/example/demo/user/UserLoader.java View File

15
     public void run(ApplicationArguments args) throws Exception {
15
     public void run(ApplicationArguments args) throws Exception {
16
         User user = new User("kiki");
16
         User user = new User("kiki");
17
         repository.save(user);
17
         repository.save(user);
18
+
19
+        User user2 = new User("Dee");
20
+        user2.setActive(true);
21
+        repository.save(user2);
18
     }
22
     }
19
 }
23
 }

+ 10
- 0
src/main/java/com/example/demo/user/UserRepository.java View File

1
 package com.example.demo.user;
1
 package com.example.demo.user;
2
 
2
 
3
 
3
 
4
+import org.springframework.data.jpa.repository.Query;
4
 import org.springframework.data.repository.CrudRepository;
5
 import org.springframework.data.repository.CrudRepository;
6
+import org.springframework.data.repository.query.Param;
5
 import org.springframework.stereotype.Repository;
7
 import org.springframework.stereotype.Repository;
6
 
8
 
9
+import java.util.List;
10
+import java.util.Optional;
11
+
7
 @Repository
12
 @Repository
8
 public interface UserRepository extends CrudRepository<User, Long> {
13
 public interface UserRepository extends CrudRepository<User, Long> {
14
+
15
+    User findByName(String name);
16
+
17
+    List<User> findAllByActive(Boolean active);
18
+
9
 }
19
 }