gpt4 book ai didi

java - SPRING DATA JPA 保存@OneToMany 关系

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:15:35 24 4
gpt4 key购买 nike

我尝试使用一对多关系来保留父实体:

@Entity
public class TrainEx {
private Set<TrainCompositionEx> trainCompositionsByTrainId;
@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY, mappedBy = "trainByTrainId")
public Set<TrainCompositionEx> getTrainCompositionsByTrainId() {
return trainCompositionsByTrainId;
}

public void setTrainCompositionsByTrainId(Set<TrainCompositionEx> trainCompositionsByTrainId) {
this.trainCompositionsByTrainId = trainCompositionsByTrainId;
}
...
}

和子实体:

@Entity
public class TrainCompositionEx{
@Id
@ManyToOne(cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
@JoinColumn(name = "trainId", referencedColumnName = "trainId", nullable = false, insertable = true, updatable = true)
private TrainEx trainByTrainId;
....

}

所以我从 json POST 端点收到我的 TrainEx trainEx:

 @RequestMapping(method= RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<Void> addTrain(@RequestBody TrainEx trainEx) throws Exception {
trainService.add(trainEx);
return new ResponseEntity<Void>(HttpStatus.CREATED);
}

json:

 {
"trainId" : 5,
"status" : 1,
"maxWeight" : 200,
"maxLength" : 35,
"speed" : 60,
"totalWeight" : 100,
"totalLength" : 20,
"trainCompositionsByTrainId": [{
"wagonByWagonId": {"wagonId" : 2}
}]
}

在我这样保存之后:

...
@Transactional
public TrainEx add(TrainEx trainEx) {

for(TrainCompositionEx trainCompositionEx : trainEx.getTrainCompositionsByTrainId()){
trainCompositionEx.setTrainByTrainId(trainEx);
trainCompositionEx.setWagonByWagonId(
em.getReference(WagonEx.class, trainCompositionEx.getWagonByWagonId().getWagonId()));
}
return trainExRepository.save(trainEx);
}
...

但我收到了 SQL 错误:“trainid”列中的空值违反了非空约束,但如您所见,我将 trainEx 实体设置为 TrainCompositionEx,然后我在 Debug模式下停止并且 trainId 存在于那里: enter image description here那我该怎么办呢?

更新 1:我调查了日志并认为问题在父实体之前仍然存在,因为我插入到 train_composition 表中,但没有插入到 train 表中,请参阅:

Hibernate: insert into tms.public.train_composition (version, transportOrderId, wagonId, trainId) values (?, ?, ?, ?)

最佳答案

我使用 em.persist 来持久化类。我的父实体有

@JsonProperty(TIMES)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<Times> timesList = new HashSet<Times>();

当 child 有

@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL)
private Rider rider;

代码是

em.persist(rider);
for (Times t : rider.getTimes()) {
t.setRider(rider);
}

对于新骑手,对于现有骑手,我将新数据合并到旧对象中。项目在这里:https://github.com/xtien/motogymkhana-server代码来自 RiderDaoImplRiderTimes。这就是该项目的用途:http://www.gymcomp.com/eu

关于java - SPRING DATA JPA 保存@OneToMany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36163310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com