<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
@Data
public class User {
@Id
private Long id;
private String username;
private Integer age;
}
public interface UserRepository extends MongoRepository<User, Long> {
User findByUsername(String username);
}
@SpringBootTest(classes = MongoDBApplication.class)
public class ApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
public void test() throws Exception {
userRepository.deleteAll();
userRepository.save(new User(1L, "didi", 30));
userRepository.save(new User(2L, "mama", 40));
userRepository.save(new User(3L, "kaka", 50));
Assertions.assertEquals(3, userRepository.findAll().size());
User u = userRepository.findById(1L).get();
userRepository.delete(u);
Assertions.assertEquals(2, userRepository.findAll().size());
u = userRepository.findByUsername("mama");
userRepository.delete(u);
Assertions.assertEquals(1, userRepository.findAll().size());
}
}
spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test