MeetJoeBlack
MeetJoeBlack

Reputation: 2904

SPRING DATA JPA save @OneToMany relation

I try to persist parent entity with one to many relation:

@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;
    }
...
}

and child entity:

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

}

So I recieve my TrainEx trainEx from json POST endpoint:

 @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}
    }]
 } 

after I save it like that:

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

But I received SQL ERROR: null value in column "trainid" violates not-null constraint, but as you see I setted trainEx entity to TrainCompositionEx, and I stopped in debug mode and trainId exists there: enter image description here so what should I do?

UPDATE1: I investigated logs and think that problem in that childs persist before parent entity, because I insert into train_composition table, but not into train table see:

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

Upvotes: 6

Views: 19824

Answers (1)

Christine
Christine

Reputation: 5575

I use em.persist for persisting classes. My parent entity has

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

while the child has

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

The code is

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

for a new rider, for an existing rider I merge the new data into the old object. The project is here: https://github.com/xtien/motogymkhana-server The code is from RiderDaoImpl and Rider and Times. This is what the project is for: http://www.gymcomp.com/eu

Upvotes: 4

Related Questions