我有三个 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
);
一篇文章只能有一位作者,因此users
<->posts
关系已经以正常形式建立(如果我错了,请纠正我)。
评级是预定义的常量,如“坏”、“好”或“真棒”,(在实际情况下)附加数据作为评级值、描述或其他字段,为了简洁起见,我在此省略。
接下来我想将评级与用户和帖子相关联。每个帖子可以被每个用户评分一次,也可以被多个用户评分。我想出了以下关系:
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 映射中的方法,以获取(用户、评级)对的每个帖子列表(或集合或任何其他集合)。
这是我现在尝试映射它们的方式:
用户.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
),否则同一个用户可以对同一个帖子进行不同的评分。