UPD: Removed unnecessary @AssociationOverrides . Added @ManyToOne(fetch = FetchType.LAZY) to avoid modifying StackOverflowException on cascade .
I have had a similar problem lately. I found my solution with @EmbededId .
My database has a Rating table that provides a many-to-many relationship between the user and the video, so userId and movieId are foreign keys and form a composite primary key. And this table also contains some additional information.
Here is my code, I hope this helps you:
Film:
@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") private List<Rating> ratings; }
User:
@Entity @Table(name = "imdb_user") public class User { @Id @Column(name = "imdb_user_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @OneToMany(cascade = CascadeType.ALL, mappedBy = "primaryKey.user") private List<Rating> ratings; }
Rating:
@Entity @Table(name = "rating") public class Rating { @EmbeddedId private RatingId primaryKey = new RatingId(); @Column(name = "rating_value") private Integer ratingValue; }
A utility class that implements a composite identifier for a rating:
@Embeddable public class RatingId implements Serializable{ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "movie_id") private Movie movie; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "imdb_user_id") private User user; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RatingId ratingId = (RatingId) o; if (movie != null ? !movie.equals(ratingId.movie) : ratingId.movie != null) return false; return !(user != null ? !user.equals(ratingId.user) : ratingId.user != null); } @Override public int hashCode() { int result = movie != null ? movie.hashCode() : 0; result = 31 * result + (user != null ? user.hashCode() : 0); return result; } }
source share