Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.7 kB
5
Indexable
Never
/*
        2.3* dodati REST entpoint u UserController koji omogućava
        prosleđivanje parametara za kreiranje korisnika i adrese
        • kreira korisnika
        • proverava postojanje adrese
        • ukoliko adresa postoji u bazi podataka dodaje je korisniku
        • ukoliko adresa ne postoji, kreira adresu i dodaje je korisniku
        NAPOMENA: OVA METODA JE IZMENJENA U SKLADU SA ZADATKOM 3
        */

    @PostMapping("/create-user")
    public UserEntity addUserAndAddress(@RequestParam String name,
                                        @RequestParam String email,
                                        @RequestParam String street,
                                        @RequestParam String cityName,
                                        @RequestParam String countryName) {

        UserEntity user = new UserEntity(name, email);

        CityEntity city = cityRepository.findCityEntityByName(cityName)
                .orElseGet(() -> {
                    CountryEntity country = countryRepository.findCountryEntityByName(countryName)
                            .orElseGet(() -> countryRepository.save(new CountryEntity(countryName)));
                    CityEntity newCity = new CityEntity(cityName, country);
                    return cityRepository.save(newCity);
                });

        AddressEntity address = addressRepository.findByCityAndStreet(city, street)
                .orElseGet(() -> {
                    AddressEntity newAddress = new AddressEntity(street, city);
                    return addressRepository.save(newAddress);
                });

        user.setAddress(address);
        userRepository.save(user);

        return user;
    }
Leave a Comment