Miguel Ribeiro
Miguel Ribeiro

Reputation: 8184

Cascade save model not saving relationship

I have an Play2 application using eBean integrated with PostgreSQL database.

Basically I have a model TripRequest that as a list of Passengers . The use case is "A trip has several passengers".

For the TripRequest I have this model:

@Entity
public class TripRequest extends Model {

    enum Status {
        OPEN,
        PROCESSING,
        CLOSED,
        CANCELLED
    }

    @Id
    private UUID id;

    @ManyToOne
    @Column(nullable = false)
    private User owner;

    @OneToMany(mappedBy = "tripRequest")
    @JoinTable(name = "trip_passengers")
    private List<Passenger> passengers;
    (... other fields, getters and setters ...)

And this is my Passenger model:

@Entity
@Table(name = "trip_passenger")
public class Passenger extends Model {

    @ManyToOne(cascade = CascadeType.ALL)
    private TripRequest tripRequest;

    @Column(nullable = false)
    private String name;
    (... other fields, getters and setters)

So, I create a new instance of TripRequest, several instances of Passenger and set that list as the passengers of TripRequestinstance. Problem is that when I do tripRequest.save() everything in the main instance (TripRequest) gets saved but the relations are not (so the passengers list).

I read in the documentation and examples and everything is pointing me to the CascadeType.ALL in the @ManyToOne annotation but no "luck" at all

EDIT: if you think the complete classes are useful please let me know as I can post them. Just decided to keep the example short so I trimmed them.

Upvotes: 7

Views: 403

Answers (2)

Rob Bygrave
Rob Bygrave

Reputation: 4031

Your @OneToMany(mappedBy = "tripRequest") ... has no cascade = CascadeType.ALL (or CascadeType.PERSIST).

This means the save on TripRequest is not cascading on the list of passengers.

Upvotes: 1

Leo
Leo

Reputation: 2199

I think you should set tripRequest on Passenger side (cause this class actually owns the relationship) and only then save it. Something like this:

for(Passenger p : passengers){
    p.tripRequest = this;
}

Upvotes: 0

Related Questions