java - 如果数据库中存在,则重用现有 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);
}
}
}
解决方案
首先感谢所有试图提供帮助的人!
阅读@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;
}
}
推荐阅读
- android - 在 dart/flutter 项目中包含 C 文件
- npp - 如何确定帧的源图像行步长?
- firebase - Firebase 更新 apple-app-site-association
- android - Android AWS S3 库 - 同步上传
- sql - 动态Sql在子选择中使用变量
- count - SPARQL 中的 GROUP 和 COUNT
- rust - 无法移出试图反序列化 hyper::Request.body() 的借用内容
- javascript - vue js计算属性略有延迟
- django - 提交表单结果错误:当前路径 home/insert 与其中任何一个都不匹配
- react-native - React Native Navigation 抽屉未打开