Search code examples
javahibernatejpastack-overflowcascade

JPA. Stackoverflow on cascade merge


Here is my JPA structure:

Movie (look at cascade types):

@Entity
@Table(name = "movie")
public class Movie {

    @Id
    @Column(name = "movie_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    //@OneToMany(cascade = CascadeType.ALL, mappedBy = "primaryKey.movie") //stack overflow
    @OneToMany(mappedBy = "primaryKey.movie") //works fine
    private List<Rating> ratings;
    ....
}

Rating:

@Entity
@Table(name = "rating")
@AssociationOverrides({@AssociationOverride(name = "primaryKey.movie", joinColumns = @JoinColumn(name = "movie_id")),
        @AssociationOverride(name = "primaryKey.user", joinColumns = @JoinColumn(name = "imdb_user_id"))})
public class Rating {
    @EmbeddedId
    private RatingId primaryKey = new RatingId();

    @Column(name = "rating_value")
    private Integer ratingValue;
    .....
}

RatingId:

@Embeddable
public class RatingId implements Serializable{
    @ManyToOne
    private Movie movie;

    @ManyToOne
    private User user;
}

When I call entityManager.merge(Movie movie) with CascadeType.ALL I get the StackOverflowError. If remove cascading, merge call doesn't throw the error. Where may be a problem?

I think this problem related to composite primary key. There is no error when merge performed on another entities with the same one-to-many relationship, but without composite id.


Solution

  • StackOverflow was caused by cyclic relations. To avoid exception I marked keys in many-to-many table as @ManyToOne(fetch = FetchType.LAZY).

    That's how my tables look after modifications: https://stackoverflow.com/a/32544519/2089491