多对多的hibernate映射和mysql脚本 - 持久性问题 [英] Many-to-Many hibernate mapping and mysql script - persistence problem

查看:105
本文介绍了多对多的hibernate映射和mysql脚本 - 持久性问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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:



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 Mappings:



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>


推荐答案

您有双向多对多关系,所以你可以在 8.5.3。许多一对多。另请参阅 7.3.1。排序的集合用于配置比较器的方式(尽管最好在数据库端使用 order-by 执行排序)。

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).

这篇关于多对多的hibernate映射和mysql脚本 - 持久性问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆