7

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.

Miguel Ribeiro
  • 8,057
  • 20
  • 51
  • 74

2 Answers2

1

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.

Rob Bygrave
  • 3,861
  • 28
  • 28
0

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;
}
Leo
  • 2,097
  • 21
  • 35
  • 1
    I am setting the tripRequest instance on each passenger. However, when I save the tripRequest the passengers list isn't saved. A workaround I found is to save the tripRequest and then iterate thru the passengers and save each individually, but it feels "wrong" – Miguel Ribeiro Oct 26 '15 at 16:04
  • 1
    @MiguelRibeiro That is definitely wrong. I think everything will work without double save if you put `(cascade=CascadeType.ALL)` to the `@OneToMany` annotation of `TripRequest` instead of `@ManyToOne` of Passenger. Because this is the direction of the cascading. – Leo Oct 26 '15 at 16:19
  • 2
    Well... found the issue. I don't even need to set the tripRequest instance to the Passenger. So, 1st of all, the cascade must go to the `@OneToMany`. The problem is that the `Passenger` didn't have an ID member. I had to debug Play's code to see from where the NPE was coming. – Miguel Ribeiro Oct 27 '15 at 01:26