Advertisement
dburyak

mongo delete with @Query

Feb 20th, 2021
1,302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. @Data
  2. @Builder(toBuilder = true)
  3. @AllArgsConstructor
  4. @NoArgsConstructor
  5. @Document
  6. public class User {
  7.     private static final long serialVersionUID = 1L;
  8.  
  9.     @Id
  10.     private String id;
  11.     private String username;
  12. }
  13.  
  14.  
  15. @Repository
  16. public interface UserRepository extends MongoRepository<User, String> {
  17.  
  18.     @Query(delete = true, value = "{ '_id': ?0 }")
  19.     long deleteUserById(String id);
  20. }
  21.  
  22.  
  23.  
  24. @SpringBootTest
  25. public class UserTest {
  26.  
  27.     @Autowired
  28.     private UserRepository userRepository;
  29.  
  30.     @Test
  31.     void testUser() {
  32.         userRepository.deleteAll();
  33.         var savedUsers = userRepository.saveAll(List.of(
  34.                 User.builder().username("john").build(),
  35.                 User.builder().username("jane").build(),
  36.                 User.builder().username("kate").build(),
  37.                 User.builder().username("brian").build()
  38.         ));
  39.  
  40.         assertThat(userRepository.findAll().size())
  41.                 .isEqualTo(4);
  42.  
  43.         var jane = savedUsers.stream()
  44.                 .filter(u -> u.getUsername().equals("jane"))
  45.                 .findFirst().orElseThrow();
  46.  
  47.         var numDeleted = userRepository.deleteUserById(jane.getId());
  48.         assertThat(numDeleted)
  49.                 .isEqualTo(1L);
  50.  
  51.         assertThat(userRepository.findAll())
  52.                 .hasSize(3)
  53.                 .allMatch(u -> Set.of("john", "kate", "brian").contains(u.getUsername()));
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement