Grafik Krystian
Grafik Krystian

Reputation: 231

Best way to prevent duplicate rows in database

I am using hibernate , looking for best practice for avoid that same insert in database. I wrote program witch saves results of search from API depends on user input, when input is the same I have duplicated rows without id in database. It's problematic for me because in future uses. Each insert must be UNIQUE.

Part of entity model :

@Entity
@Component
public class Flight {

    private Long id;

    private String departure;

    private String currency;

    private String destination;

    private BigDecimal price;
... etc //

Save code:

        @RequestMapping(value = "/save", method = RequestMethod.GET)
        public String save(
                @ModelAttribute("FlightDTO") FlightDTO flightDTO,
                @ModelAttribute("FlightOutput") Map<String, Map<String, FlightDeserialization>> flightOutputMap,
                @ModelAttribute("HotelOutput") ArrayList<Comparison> hotelOutputList,
                @ModelAttribute("HotelGooglePlaceList") Map<Integer, List<PlacesResults>> hotelGooglePlaceList,
                @ModelAttribute("HotelGoogleImageList") Map<Integer, List<Imageresults>> hotelGoogleImageList) {


            boolean isHotelGoogleListEqualToHotelOutputList = hotelGooglePlaceList.keySet().size() == hotelOutputList.size() & hotelGooglePlaceList.keySet().size() == hotelGoogleImageList.size();


            Flight flight;
            for (String keyOut : flightOutputMap.keySet()) {

                for (String keyIn : flightOutputMap.get(keyOut).keySet()) {
                    flight = new Flight();
                    flight.setCurrency(flightDTO.getCurrency());
                    flight.setAirline(csvParser.airlineParser(flightOutputMap.get(keyOut).get(keyIn).getAirline()));
                    flight.setAirlineIata(flightOutputMap.get(keyOut).get(keyIn).getAirline());
                    flight.setDepartureTime(flightOutputMap.get(keyOut).get(keyIn).getDepartureTime());
                    flight.setReturnTime(flightOutputMap.get(keyOut).get(keyIn).getReturnTime());
                    flight.setFlightNumber(flightOutputMap.get(keyOut).get(keyIn).getFlightNumber());
                    flight.setPrice(flightOutputMap.get(keyOut).get(keyIn).getPrice());
                    flight.setExpiresAt(flightOutputMap.get(keyOut).get(keyIn).getExpiresAt());
                    flight.setDestination(flightDTO.getDestination());
                    flight.setDeparture(flightDTO.getDeparture());
                    flight.setUserName(CurrentUserName().getUsername());

                    if (isHotelGoogleListEqualToHotelOutputList) {
                        Hotel hotel;
                        BigDecimal exchangeRate = currencyRepository.findByName(flightDTO.getCurrency()).getExchangeRate();
                        for (int i = 0; i < hotelOutputList.size(); i++) {
                            Comparison array = hotelOutputList.get(i);
                            hotel = new Hotel();


                            hotel.setImage(hotelGoogleImageList.get(i).get(1).getImage());
                                            hotel.setHotelLink(hotelGoogleImageList.get(i).get(0).getLink());



                            hotel.setLatitude(hotelGooglePlaceList.get(i).get(0).getGps_coordinates().getLatitude());
                            hotel.setLongitude(hotelGooglePlaceList.get(i).get(0).getGps_coordinates().getLongitude());


hotel.setCurrency(flightDTO.getCurrency());
hotel.setName(array.getHotel());
hotel.setSite(array.getVendor1());
hotel.setSite(array.getVendor2());
                            hotel.setPrice(hotelCurrencyService.amountCalculator(array.getVendor1Price(), exchangeRate));
                            hotel.setPrice(hotelCurrencyService.amountCalculator(array.getVendor2Price(), exchangeRate));
                            hotel.setPrice(hotelCurrencyService.amountCalculator(array.getVendor3Price(), exchangeRate));


flight.setHotel(hotel);
flightRepository.save(flight);

I have tried used @UniqueConstraint , and @Unique, but I guess it intended for something else.

Please Help me !

Upvotes: 0

Views: 4645

Answers (2)

Bor Laze
Bor Laze

Reputation: 2506

First, you don't need @Component on your entity.

Second, add this annotation

@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames ={"id", "departure", ...})})

with fields that should not be duplicated.

NB: you need to add spring.jpa.hibernate.ddl-auto=update to application.properties

Upvotes: 2

fiveobjects
fiveobjects

Reputation: 4269

Adding @UniqueConstraint to the ORM does not help as hibernate won't check for uniqueness. There are two ways - add a unique constraint to the database table and/or implement duplicate entry check yourself in code.

In case you add the unique constraint to the database table handle constraint violation exception.

Upvotes: 0

Related Questions