I created a spring boot app with application.properties
containing this:
spring.data.mongodb.uri=mongodb://localhost:27017/product-service
I also added a new connection in my MongoDB Compass with this URI:
mongodb://localhost:27017/product-service
But for some reason, I get NPE when I try to get something from the repo.
I did a little bit of research and did the following steps to fix the issue, but I couldn't solve it:
- I verified that MongoDB is running by accesing the URI
- I made sure that I created a database with this name "product-service" in MongoDB Compass.
- When I enable MongoDB logging I see nothing related to mongo.
Here are the logs when I try to get something from the repository:
java.lang.NullPointerException: null
at com.emanuel.productservice.controller.ProductController.getAllProducts(ProductController.java:29) ~[main/:na]
Here is my controller:
@RestController
@RequestMapping("api/product")
@RequiredArgsConstructor
public class ProductController {
private ProductService productService;
@GetMapping
@ResponseStatus(HttpStatus.OK)
public List<ProductResponse> getAllProducts(){
return productService.getAllProducts();
}
}
Here is my service:
@Service
@RequiredArgsConstructor
@Slf4j
public class ProductService {
private final ProductRepo productRepo;
public List<ProductResponse> getAllProducts() {
List<Product> products = productRepo.findAll(); // here is the line where I get NPE
return products.stream().map(this::mapToProductResponse).collect(Collectors.toList());
}
}
Here is my repository:
public interface ProductRepo extends MongoRepository<Product, String> {
}
I have MongoDB Community Server version 6.0.4 (current) & Spring Boot 2.7.8. This is the dependency that I use in Gradle:
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb