JPA——独特的双向实体关系
我想在我的“标签”实体之间建立关系。这些关系是双向的,并存储在我的实体“TagRelation”中:
每个标签关系应该只具有tag_relations 表中有 1 个条目,因为关系的方向没有意义。例如,如果我插入:
“森林”(标签 1)<-> “树”(标签 2)
我不应该能够以相反的方式插入关系:
“树”(标签 1)<-> “Forest”(标签 2)
这是表 tag_relation 的 SQL 代码:
CREATE TABLE IF NOT EXISTS `tag_relation` (
id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`tag_id_1` INT(10) UNSIGNED NOT NULL ,
`tag_id_2` INT(10) UNSIGNED NOT NULL ,
`type` ENUM('related_subject','synonymous','alternative_writing') NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_tag_1` (`tag_id_1` ASC) ,
INDEX `fk_tag_2` (`tag_id_2` ASC) ,
UNIQUE INDEX `ux_relation_1_2` (`tag_id_1` ASC, `tag_id_2` ASC) ,
UNIQUE INDEX `ux_relation_2_1` (`tag_id_2` ASC, `tag_id_1` ASC) ,
CONSTRAINT `fk_tag_1`
FOREIGN KEY (`tag_id_1` )
REFERENCES `mm`.`tag` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_tag_2`
FOREIGN KEY (`tag_id_2` )
REFERENCES `mm`.`tag` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 1
现在的唯一索引不会强制执行我想要的唯一关系。如何在我的数据库中强制执行此操作?
I want to make relations between my "Tag" entity. The relationships are bi-directional and are stored in my entity "TagRelation":
Each tag relation should only have 1 entry in the tag_relations table, since the direction of the relation has no meaning. For example if I insert:
"Forest" (tag 1) <-> "Tree" (tag 2)
I should not be possible to insert the relationship the other way around:
"Tree" (tag 1) <-> "Forest" (tag 2)
This is the SQL code of the table tag_relation:
CREATE TABLE IF NOT EXISTS `tag_relation` (
id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`tag_id_1` INT(10) UNSIGNED NOT NULL ,
`tag_id_2` INT(10) UNSIGNED NOT NULL ,
`type` ENUM('related_subject','synonymous','alternative_writing') NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_tag_1` (`tag_id_1` ASC) ,
INDEX `fk_tag_2` (`tag_id_2` ASC) ,
UNIQUE INDEX `ux_relation_1_2` (`tag_id_1` ASC, `tag_id_2` ASC) ,
UNIQUE INDEX `ux_relation_2_1` (`tag_id_2` ASC, `tag_id_1` ASC) ,
CONSTRAINT `fk_tag_1`
FOREIGN KEY (`tag_id_1` )
REFERENCES `mm`.`tag` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_tag_2`
FOREIGN KEY (`tag_id_2` )
REFERENCES `mm`.`tag` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 1
The unique indexes as they are now do not enforce the unique relationship that I want. How can I enforce this in my database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关系类型在运行时是动态的吗?如果不是,我认为你最好将关系直接放在标签中:
这将使你的关系更安全,甚至更高效。
Are the relation types dynamic at runtime? if not I think you would be better placing the relationships directly in the tag:
This will make your relations more secure and even more performant.