Przeglądaj źródła

add crud controller

Nhu Nguyen 6 lat temu
rodzic
commit
56a4ae753a

+ 2
- 0
src/main/java/com/example/demo/DemoApplication.java Wyświetl plik

@@ -2,6 +2,8 @@ package com.example.demo;
2 2
 
3 3
 import org.springframework.boot.SpringApplication;
4 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 8
 @SpringBootApplication
7 9
 public class DemoApplication {

+ 24
- 0
src/main/java/com/example/demo/user/UserController.java Wyświetl plik

@@ -0,0 +1,24 @@
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 Wyświetl plik

@@ -15,5 +15,9 @@ public class UserLoader implements ApplicationRunner{
15 15
     public void run(ApplicationArguments args) throws Exception {
16 16
         User user = new User("kiki");
17 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 Wyświetl plik

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