java - 防止数据库中重复行的最佳方法

标签 java spring hibernate jpa

我正在使用 hibernate ,寻找最佳实践以避免在数据库中进行相同的插入。我编写了程序,根据用户输入保存来自 API 的搜索结果,当输入相同时,我在数据库中复制了没有 id 的行。这对我来说是个问题,因为在未来的使用中。 每个插入必须是唯一的。

实体模型的一部分:

@Entity
@Component
public class Flight {

    private Long id;

    private String departure;

    private String currency;

    private String destination;

    private BigDecimal price;
... etc //

保存代码:

        @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);

我尝试过使用 @UniqueConstraint 和 @Unique,但我猜它是用于其他用途。

请帮助我!

最佳答案

首先,您的实体上不需要 @Component

二、添加这个注解

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

包含不应重复的字段。

注意:您需要将 spring.jpa.hibernate.ddl-auto=update 添加到 application.properties

关于java - 防止数据库中重复行的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57238457/

相关文章:

java - HttpURLConnection 未返回所有 header

java - 是否可以将 PostgreSQL 中的字符字段转换为 JPA 命名查询中的整数?

spring - cxf 和 spring MVC : No service was found

java - 为什么 Californium 在使用 CoAP 协议(protocol)发送数据时会在 65535 条记录后等待

java - 使用 Hibernate Query.list() 避免类型安全警告

java - Spring 绑定(bind)结果错误

java - Spring等各种java框架中Annotations有什么用?

java - Embeddable 和 EmbeddedId 之间的 JPA 映射 @ManyToOne

java - JPA AttributeConverter 被忽略

spring boot - 计算字段