标签:os 文件 amp sp on ad c type app
Hibernate
Hibernate多对多关联映射通常别拆分成两个多对一关联映射
1、 下面的HostBean、UserBean、UserHostBean,UserHostBean是两个表之间的关联表,分别跟HostBean和UserBean都是多对一的关联关系,可以发现中间表始终是多的一端。
2、因此配置文件中是这样的,在中间表UserHostBean中
<many-to-one name="user" class="UserBean" not-null="true" lazy="false">
<column name="user_id" />
</many-to-one>
<many-to-one name="host" class="HostBean" not-null="true" lazy="false">
<column name="host_id" />
</many-to-one>
分别设置中间表的两个关联字段;在另外本身是多对多关联的两个表中
<set name = "users" lazy="false" cascade="save-update" inverse="true">
<key column="user_id"></key>
<one-to-many class="UserHostBean"/>
</set>
<set name="hosts" lazy="false" cascade="save-update" inverse="true">
<key column="host_id"></key>
<one-to-many class="UserHostBean"/>
</set>
这个column:user_id是由一指向多的那端的一个维护关系字段,因此跟many-to-one中的关联字段名称要一致
3、 关联的CRUD操作:
Create:原则还是跟多对一样,先保存多的一端然后再保存一端,分别setHost和setUser,从而在这两者间建立关联
Example:
HostBean:
<hibernate-mapping>
<class name="HostBean" table="t_host">
<id name="id" column="id" type="integer">
<generator class="increment"></generator>
</id>
<set name = "users" lazy="false" cascade="save-update" inverse="true">
<key column="user_id"></key>
<one-to-many class="UserHostBean"/>
</set>
</class>
</hibernate-mapping>
UserBean
<hibernate-mapping>
<class name="UserBean" table="users">
<id name="id" column="id" type="integer">
<generator class="increment"></generator>
</id>
<set name="hosts" lazy="false" cascade="save-update" inverse="true">
<key column="host_id"></key>
<one-to-many class="UserHostBean"/>
</set>
</class>
</hibernate-mapping>
UserHostBean
<hibernate-mapping>
<class name="UserHostBean" table="t_user_host">
<id name="id" column="id" type="integer">
<generator class="increment"></generator>
</id>
<property name="lastVisitDate" column="last_visit_date" type="string"/>
<many-to-one name="user" class="UserBean" not-null="true" lazy="false">
<column name="user_id" />
</many-to-one>
<many-to-one name="host" class="HostBean" not-null="true" lazy="false">
<column name="host_id" />
</many-to-one>
</class>
</hibernate-mapping>
标签:os 文件 amp sp on ad c type app
原文地址:http://www.cnblogs.com/Struts-pring/p/3937741.html