3 つの SQL テーブルがあります。
create table users (
id serial primary key,
name text not null unique
);
create table posts (
id serial primary key,
data text not null,
authorId integer not null references users (id)
);
create table ratings (
id serial primary key,
name text not null unique
);
1 つの投稿には作成者が 1 人しかいないため、users
<->posts
関係は通常の形式で既に確立されています (間違っていたら訂正してください)。
評価は、「悪い」、「良い」、「素晴らしい」などの事前定義された定数であり、(実際の場合) 評価値、説明、またはその他のフィールドとして追加のデータがあり、簡潔にするためにここでは省略されています。
次に、評価をユーザーと投稿に関連付けたいと思います。各投稿は、各ユーザーが 1 回評価することも、複数のユーザーが評価することもできます。私は次の関係を思いついた:
create table posts_ratings_users_map (
postId integer not null references posts (id),
ratingId integer not null references ratings (id),
userId integer not null references users (id),
primary key (postId, ratingId, userId)
);
しかし、ここに問題があります: Hibernate ORM マッピング内に統合して、(User,Rating) のペアの各投稿リスト (またはセット、またはその他のコレクション) を取得する方法がわかりません。
これが私が今それらをマッピングしようとしている方法です:
ユーザー.java:
@Entity(name = "users")
public class User {
@Id
@Column(nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false)
private String name;
@OneToMany
@JoinColumn(name = "authorId")
private Set<Post> posts = new HashSet<>();
// ...
// getters and setters
// ...
}
評価.java:
@Entity(name = "ratings")
public class Rating {
@Id
@Column(nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false)
private String name;
@ManyToMany(mappedBy = "ratings")
private Set<Post> posts = new HashSet<>();
// ...
// getters and setters
// ...
}
Post.java:
@Entity(name = "posts")
public class Post {
@Id
@Column(nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false)
private String data;
@ManyToOne
@JoinColumn(name = "authorId")
private User author;
@ManyToMany
@JoinTable(
name = "posts_ratings_users_map",
joinColumns = { @JoinColumn(name = "ratingId") },
inverseJoinColumns = { @JoinColumn(name = "postId") }
)
private Set<Rating> ratings = new HashSet<>(); // here is the problem. i can relate ratings to this post, but how
// do i relate them with users which assigned their ratings to this
// post ?
// ...
// getters and setters
// ...
}
評価とユーザーのペアのリストを各投稿に関連付けるには、何を変更する必要がありますか?
UPD1
明らかなエラー: posts_ratings_users_map の PK は(postId, userId)
(を除くratingId
) にする必要があります。そうしないと、同じユーザーが同じ投稿に異なる評価を付けることができました。