以一种非常简单的方式,我尝试创建以下结构:
Table Post
id (PK)
name
content
Table Tag
post_id (FK to post id)
name
这样一个帖子可能有很多标签,但这些标签没有主 ID。 (到目前为止,主键是复合的 post_id + name)
现在我想知道这是否是一个不好的做法(省略标签表中的 id 列)以及使用 hibernate 时用作标签表主键的可能值是什么。
最佳答案
规范化数据库中的每一行都有一个主键。这是必须。
post_id
感觉像是一个外键,应该引用帖子表 id
主键。
我不太关心这个设计。一个帖子可以有多个标签;一个标签可以应用于许多帖子。它应该是带有连接表的多对多设计。
create table post (
id int not null auto_increment,
text varchar(140),
primary key id
);
create table tag (
id int not null auto_increment,
name varchar(80) not null,
primary key id
);
create table post_tag (
post_id int,
tag_id int,
primary key(post_id, tag_id),
foreign key(post_id) references post(id),
foreign key(tag_id) reference tag(id)
);
关于java - Hibernate - 在子表上没有 ID 的情况下,我应该在一对多关系中使用什么主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23208977/