Mongodb Labs:spring-boot-starter-data-mongodb

Connect to Atlas Mongodb

second attempt with spring-boot-starter-data-mongodb

Dependency

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Defining properties

app.uri=mongodb+srv://<user>:<password>@cluster0.<namecluster>.mongodb.net/electrolinera
app.database=electrolinera

Extending repository

@Repository
public interface ReservationRepository extends MongoRepository<Reservation, String> {

Get Data from controller

import com.example.mongodb2.model.Reservation;
import com.example.mongodb2.repository.ReservationRepository;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class ReservationController {
        
  @Autowired
  ReservationRepository reservationRepository;
  
  
  @GetMapping("/reservations")
  public ResponseEntity<List<Reservation>> getAllReservations(@RequestParam(required = false) Integer idUser) {
    try {
    List<Reservation> reservations = new ArrayList<Reservation>();

    if (idUser == null)
      reservationRepository.findAll().forEach(reservations::add);
    else
      reservationRepository.findByIdUser(idUser).forEach(reservations::add);

    if (reservations.isEmpty()) {
      return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    return new ResponseEntity<>(reservations, HttpStatus.OK);
  } catch (Exception e) {
        System.out.println(e.getMessage());
    return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
  }
  }
  
}

Result

fig 1