由于某种原因,这不会将任何内容持久保存到 tag_item 表中:
Tag tag = new Tag();
tag.setName("test");
tag = (Tag) tagService.save(tag);
Set<Tag> tags = new HashSet<Tag>();
tags.add(tag);
Item item = itemService.getByStringId(2);
item.setTags(tags);
itemService.save(item);
MySQL:
CREATE TABLE `tags` (
`tag_id` bigint(20) NOT NULL auto_increment,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `tag_item` (
`tag_id` bigint(20) NOT NULL,
`item_id` bigint(20) NOT NULL,
PRIMARY KEY (`item_id`,`tag_id`),
KEY `FK_tag_item_tag_id` (`tag_id`),
KEY `FK_tag_item_item_id` (`item_id`),
CONSTRAINT `FK_tag_item_tag_id` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`tag_id`),
CONSTRAINT `FK_tag_item_item_id` FOREIGN KEY (`item_id`) REFERENCES `items` (`item_id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `items` (
`item_id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`item_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
Xml Hibernate 映射:
<id name="id" type="long" column="tag_id">
<generator class="native"/>
</id>
<property name="name" type="string" column="name"/>
<set name="items" inverse="true" lazy="true" table="tag_item">
<key>
<column name="tag_id" not-null="true"/>
</key>
<many-to-many class="com.iteezy.shared.domain.Item">
<column name="item_id" not-null="true"/>
</many-to-many>
</set>
<小时/>
<id name="id" type="long" column="item_id">
<generator class="native"/>
</id>
<property name="name" type="string" column="name"/>
<set name="tags" inverse="true" lazy="true" table="tag_item">
<key>
<column name="item_id" not-null="true"/>
</key>
<many-to-many class="com.iteezy.shared.domain.Tag">
<column name="tag_id" not-null="true"/>
</many-to-many>
</set>
最佳答案
您有双向多对多关系,因此您可以使用 8.5.3. Many-to-many 中的示例。另请参阅7.3.1. Sorted collections了解配置比较器的方法(尽管最好在数据库端使用 order-by
执行排序)。
关于mysql - 多对多hibernate映射和mysql脚本-持久化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5407102/