首页 > 解决方案 > 如果数据库中存在,则重用现有 id

问题描述

我想做以下事情:

使用 JPA 将 CityHistory 插入数据库。第一次没有数据,所以会插入一个新的城市。(IT WORKS FINE) city 表中的 (IDENTIFICATION) 是一个唯一字段。

我想要实现的是,当我再次插入同一个城市时,是重用现有字段而不是尝试创建一个新字段(标识就像一个城市的唯一名称)。

那么如何使用 JPA 或 Hibernate 来做到这一点呢?

@Entity
public class CityHistory extends History implements Serializable {

    @Id
    @Column(name = "KEY_CITY_HISTORY", nullable = false, precision = 19)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "CITY_ID", nullable = false, foreignKey = @ForeignKey(name = "FK_CITY_ID"))
    private City cityId;

    @Column(name = "CITY_NAME", nullable = false)
    private String cityName;
}


@Entity
public class City implements Serializable {

    @Id
    @Column(name = "KEY_CITY", nullable = false, precision = 19)
    private Long id;

    @Column(name = "IDENTIFICATION", nullable = false, unique = true)
    private String identification;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "MUNICIPALITY_ID", foreignKey = @ForeignKey(name = "FK_MUNICIPALITY_ID"))
    private Municipality municipalityId;
}

更新 这是我将数据写入数据库的方式,它是一个 Spring Batch itemWriter

@Component
public class InfoItemWriter implements ItemWriter<Object> {

    @Autowired
    private CityHistoryRepository cityHistoryRepository;

    @Override
    public void write(List<? extends Object> items) throws Exception {

        if (items.size() > 0 && items.get(0) instanceof CityHistory) {
            cityHistoryRepository.saveAll((List<? extends CityHistory>) items);
        }
    }
}

标签: javahibernatejpaspring-data-jpa

解决方案


首先感谢所有试图提供帮助的人!

阅读@Benjamin Maurer提供的资源:

我不认为你想要 ManyToOne 端的级联,请参阅一对多

最常见的父子关联由一对多和多对一关系组成,其中级联仅对一对多方有用

由于我的关系是 ManyToOne,因此使用级联确实没有用,也不能满足我的需要。

我使用了不同的方法来达到目标​​。我创建了一个服务,它验证一个城市的存在,如果它不存在,则添加一个新城市。

@Service
public class CityHistoryServiceImpl implements CityHistoryService {
    @Autowired
    CityRepository cityRepository;
    @Autowired
    CityHistoryRepository cityHistoryRepository;

    @Override
    public Optional<CityHistory> addCityHistory(City city, String cityName, ..) {

        if (city != null && cityName != null) {

            City city1 = addCityIfNotExist(city);

            CityHistory cityHistory = new CityHistory();
            cityHistory.setCityId(city1);
            cityHistory.setCityName(cityName);

            cityHistoryRepository.save(cityHistory);
            return Optional.of(cityHistory);
        }
        return Optional.empty();
    } ....

    private City addCityIfNotExist(City city) {
        City city1 = cityRepository.findFirstByBagId(city.getBagId());
        if (city1 == null) {
            city1 = cityRepository.save(city);
        }
        return city1;
    }
}

推荐阅读