Java persistence (Ebean) serialize generated value to Json

401 views Asked by At

I have two entities and OneToMany relationship between them. First:

@Entity
public class Trip extends Model {

    ...

    @OneToMany(cascade = CascadeType.ALL)
    public List<Category> categories = new ArrayList<>();
}

The second one:

@Entity
public class Category extends Model {

    ...

    @ManyToOne
    public Trip trip;
}

So, Ebean automatically generates the trip_id column for the Category table.

Now I need to serialize Category entity/object to JSON (with trip_id including). How can I do it? I was trying to manually create trip_id field, but received the duplicate exception.

1

There are 1 answers

1
rtruszk On

You have one-directional relations. You should change them to bi-directional. So there should be:

@Entity
public class Trip extends Model {

    ...

    @OneToMany(cascade = CascadeType.ALL, mappedBy="trip")
    public List<Category> categories = new ArrayList<>();
}

@Entity
public class Category extends Model {

    ...

    @ManyToOne
    public Trip trip;

    @OneToMany(mappedBy="category")
    public List<Place> places = new ArrayList<>();
}

@Entity
public class Place extends Model {

    ...

    @ManyToOne
    public Category category;

}