I am trying to build a structure as shown below:
User:
id | username |
------------------
1 | Mary |
2 | George |
3 | Candy |
Movie:
id | name |
----------------------------
1 | Slumdog Millionaire |
2 | Avatar |
3 | Star Trek |
Rating:
user_id | movie_id | rate |
------------------------------
1 | 1 | 6 |
2 | 3 | 8 |
3 | 2 | 9 |
A user can only rate the same movie once. I think I should make user_id
- movie_id
pairs in the rating
table Primary Key.
And use one-to many relationships between user
- rating
and movie
- rating
entities. Is that true?
I have not enough experience for Hibernate and the examples are generally shows default one-to many relationships. But I think I need a composite key relationship. So, is there an example for this scenario? I searched many of them but I need to find the correct approach and follow it. Thanks in advance.
Update: By using @Embeddedable
I updated related entities as shown below:
User:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Rating> ratings = new HashSet<>();
public void addRating(Rating rating) {
ratings.add(rating);
}
public void removeRating(Rating rating) {
ratings.remove(rating);
}
// Getters, setters, constructors and equals methods
}
Movie:
@Entity
@Table(name = "movie")
public class Movie {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@OneToMany(mappedBy = "movie", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Rating> ratings = new HashSet<>();
public void addRating(Rating rating) {
ratings.add(rating);
}
public void removeRating(Rating rating) {
ratings.remove(rating);
}
// ...
}
@Entity
@Table(name = "rating")
public class Rating {
@EmbeddedId
private RatingId ratingId;
private int rate;
@ManyToOne(fetch = FetchType.LAZY)
private User user;
@ManyToOne(fetch = FetchType.LAZY)
private Movie movie;
}
RatingId:
@Embeddable
public class RatingId implements Serializable {
private Long userId;
private Long movieId;
// ...
}