Lasse
Lasse

Reputation: 141

Java Spring JPA magical update

I am having two Entities: Aircraft

import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
//@ToString
public class Aircraft extends AbstractPersistable<Long> {

    private String name;
    @ManyToOne
    private Airport airport;

    @Override
    public String toString(){
        return name;
    }
}

And Airport:

public class Airport extends AbstractPersistable<Long> {

    private String identifier;
    private String name;
    @OneToMany(mappedBy = "airport")
    private List<Aircraft> aircrafts = new ArrayList<>();

    @Override
    public String toString(){
        String aircraftString = aircrafts.stream().map(r -> r.toString()).collect(Collectors.joining(", "));
        return "airport " + name + " " + "[" + aircraftString + "]";
    }
}

And a @PostMapping in @Controller like this:

@PostMapping("/aircrafts/{aircraftId}/airports")
    public String assignAirport(@RequestParam Long airportId,@PathVariable Long aircraftId){
        Aircraft aircraft = aircraftRepository.getOne(aircraftId);
        Airport airport = airportRepository.getOne(airportId);

        aircraft.setAirport(airport);
        aircraftRepository.save(aircraft)
        System.out.println(airport.toString());
        System.out.println(aircraft.toString());
        return "redirect:/aircrafts";
    }

This works. But I can not figure out how does this

private List<Aircraft> aircrafts = new ArrayList<>();

List get updated? I first figured it should work like this in @Controller

airport.getAircrafts().add(aircraft);

But that does not do anything.

Upvotes: 1

Views: 136

Answers (1)

Hesham Osman
Hesham Osman

Reputation: 111

The OneToMany relation in the airport class only reflecting what is persisted in the ManyToOne relation in the aircraft class so whenever you will add a new plane that has an airport, this airport planes List will be updated. Side Note: If you want to achieve the behavior you were expecting you can add

 @OneToMany(mappedBy = "airport", cascade = CascadeType.ALL)
 private List<Aircraft> aircrafts = new ArrayList<>();

 public void addAircraft(Aircraft aircraft){
     aircraft.setAirport(this);
     aircrafts.add(aircraft);
 }

to your airport class and then save the airport entity. but I think this isn't what you want and also it's not beneficial in your current case

Upvotes: 1

Related Questions