Answer the question
In order to leave comments, you need to log in
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;
}
}
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;
}
//выше получена погода
w.setCity(new City("Rostov-on-Don"));
w.setWeatherSource(new WeatherSource("openWeather"));
weatherService.add(w);
Answer the question
In order to leave comments, you need to log in
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);
How to make hibernate not try to add an entry to the city table if the desired city is already there?
orElseThrow()
throw an exception in the RuntimeException method that such a city exists. You can create your own type exception: CityExistsException
boolean existsByCityName(String cityName);
And then also if true, then throw an exception
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question