S
S
Sergei Chamkin2020-12-07 18:19:48
Java
Sergei Chamkin, 2020-12-07 18:19:48

Hibernate @ManyToOne how to not create an entry if it's already created?

There are three entities
City and Weather Source (they are identical):

public class City {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(unique = true, nullable = false)
    private String cityName;

    public City(String cityName) {
        this.cityName = cityName;
    }
}

Weather:
public class Weather {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private LocalDateTime date;
    private double temp;
    private double humidity;
    private int pressure;
    private String weatherDescription;

    @ManyToOne
    @JoinColumn(name="weather_source_id")
    private WeatherSource weatherSource;

    @ManyToOne
    @JoinColumn(name="city_id")
    private City city;
}


When adding weather with a city that already exists in the city, we get an error:
//выше получена погода
        w.setCity(new City("Rostov-on-Don"));
        w.setWeatherSource(new WeatherSource("openWeather"));
        weatherService.add(w);

ERROR: Duplicate key value violates unique constraint "uk_djnk44fptegbsu6drhc9xvlfj"

Details: Key "(city_name)=(Rostov-on-Don)" already exists.
How to make hibernate not try to add an entry to the city table if the desired city is already there?
I tried to use only the name value in equals and hasCode. Is it really necessary to simply pull out the city by name from the service and add it to the weather before adding it? can't it be done automatically?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2020-12-07
@Sergei1337

Hello!
1) In the repository for City (presumably CityRepository or CityDao), add a method that will return you a City object by its name.

Optional<City> findCityByCityName(String cityName);

something like this
2) Next
How to make hibernate not try to add an entry to the city table if the desired city is already there?

Now, in the service level, you pull out a city by its name and if there is none, then add it, and if there is such a city, then you can orElseThrow()throw an exception in the RuntimeException method that such a city exists. You can create your own type exception: CityExistsException
If you do not want to use Optional, then you can create a method in the repository boolean existsByCityName(String cityName);And then also if true, then throw an exception

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question