10 Mayıs 2023 Çarşamba

SpringData MongoDB Reactive ReactiveMongoRepository Arayüzü

Giriş
Bazı metodlar şöyle
Flux<T> findAll()
Flux<T> save()
Mono<T> findById(ID id) 
Mono<Void> deleteById (ID id)
Kullanım
Örnek
Şöyle yaparız
@RestController
@RequestMapping("/employees")
public class EmployeeController {
  private final EmployeeRepository employeeRepository;
  public EmployeeController(EmployeeRepository employeeRepository) {
    this.employeeRepository = employeeRepository;
  }
  @GetMapping
  public Flux<Employee> getAllEmployees() {
    return employeeRepository.findAll();
  }
  @PostMapping
  public Mono<Employee> createEmployee(@RequestBody Employee employee) {
    return employeeRepository.save(employee);
  }
  @GetMapping("/{id}")
  public Mono<Employee> getEmployeeById(@PathVariable String id) {
    return employeeRepository.findById(id);
  }
  @PutMapping("/{id}")
  public Mono<Employee> updateEmployee(@PathVariable String id,
                                             @RequestBody Employee employee) {
      return employeeRepository.findById(id)
        .flatMap(existingEmployee -> {
          existingEmployee.setName(employee.getName());
          existingEmployee.setDepartment(employee.getDepartment());
          return employeeRepository.save(existingEmployee);
        });
    }
  @DeleteMapping("/{id}")
  public Mono<Void> deleteEmployee(@PathVariable String id) {
    return employeeRepository.deleteById(id);
  }
}
Pagination
Örnek
Şöyle yaparız
@Repository
public interface EmployeeRepository extends ReactiveMongoRepository<Employee, String> {
    Flux<Employee> findByName(String name, Pageable pageable);
}

@RestController
@RequestMapping("/employees")
public class EmployeeController {
  // existing code
  @GetMapping("/search")
  public Flux<Employee> searchEmployees(@RequestParam("name") String name,
                            @RequestParam(value = "page", defaultValue = "0") int page,
                            @RequestParam(value = "size", defaultValue = "10") int size) {
    PageRequest pageable = PageRequest.of(page, size, Sort.by("name"));
    return employeeRepository.findByName(name, pageable);
  }
}
flatMap metodu
Örnek
Şöyle yaparız. Burada update için kullanılıyor
@PutMapping("/{id}")
public Mono<Employee> updateEmployee(@PathVariable String id,
                                     @RequestBody Employee employee) {
  return employeeRepository.findById(id)
    .flatMap(existingEmployee -> {
      existingEmployee.setName(employee.getName());
      existingEmployee.setDepartment(employee.getDepartment());
      return employeeRepository.save(existingEmployee);
    });
}
Örnek
Elimizde iki tane ReactiveCrudRepository'den  kalıtan repository olsun
@Autowired
private CurrencyRepository currencyRepository;

@Autowired
private CurrencyArchiveRepository currencyArchiveRepository;
Şöyle yaparız
@Override
@Transactional
public Mono<Void> delete(final String currencyCode) {
  final CurrencyArchive currencyArchive = buildCurrencyArchive();

  return this.currencyArchiveRepository.save(currencyArchive)
      .flatMap(c -> this.currencyRepository.delete(c.getCode()))
      .then();
}
@Query İle Kullanımı
Şeklen şöyle

Açıklaması şöyle
‘?0’ indicates that the mentioned property should be equal to the zeroth parameter to the query method. Further, if there were more parameters, they could be referred to ?1, ?2, and so forth.
Örnek
Şöyle bir repository olsun
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;

@Repository
public interface FreelancerRepository extends ReactiveMongoRepository<Freelancer, String> {

    @Query("{ 'skills': { $all: ?0 } }")
    Flux<Freelancer> findBySkillsAll(List<String> skills);

    Flux<Freelancer> findBySkillsIn(List<String> skills);

}
Şöyle yaparız
@Service
public class FreelancerService {

  @Autowired
  private FreelancerRepository repository;

  public Flux<Freelancer> findBySkillsOne(final List<String> skills){
    return this.repository.findBySkillsIn(skills);
  }

  public Flux<Freelancer> findBySkillsAll(final List<String> skills){
    return this.repository.findBySkillsAll(skills);
  }

  public Mono<Freelancer> getPerson(final String id){
    return this.repository.findById(id);
  }

  public Mono<Freelancer> savePerson(final Freelancer person){
    return this.repository.save(person);
  }

  public Mono<Freelancer> updatePerson(final Freelancer person){
    return this.repository.findById(person.getId())
      .map(p -> person)
      .flatMap(this.repository::save);
  }

  public Mono<Void> deletePerson(final String id){
    return this.repository.deleteById(id);
  }
}


Hiç yorum yok:

Yorum Gönder