Many-to-Many hibernate mapping and mysql script - persistence problem
For some reason this is not persisting anything into tag_item table :
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,
P开发者_如何学运维RIMARY 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 Mappings:
<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>
You have a bidiectional many-to-many relationship, so you can use an example in 8.5.3. Many-to-many. Also see 7.3.1. Sorted collections for the way to configure a comparator (though it would be better to perform sorting at the database side with order-by
).
精彩评论