多对多关联映射 (many-to-many)
多对多关联映射,需要一个中间表,Hibernate会自动生成中间表
一、多对多单向
Role.hbm.xml
<hibernate-mapping> <class name="com.bjsxt.hibernate.Role" table="t_role"> <id name="id"> <generator class="native"/> </id> <property name="name"/> </class> </hibernate-mapping>
User.hbm.xml
<hibernate-mapping> <class name="com.bjsxt.hibernate.User" table="t_user"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <set name="roles" table="t_user_role"> <key column="userid"/> <many-to-many class="com.bjsxt.hibernate.Role" column="roleid"/> </set> </class> </hibernate-mapping>
二、多对多双向
Role.jbm.xml
<hibernate-mapping> <class name="com.bjsxt.hibernate.Role" table="t_role"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <set name="users" table="t_user_role" order-by="userid"> <key column="roleid"/> <many-to-many class="com.bjsxt.hibernate.User" column="userid"/> </set> </class> </hibernate-mapping>
User.hbm.xml
<hibernate-mapping> <class name="com.bjsxt.hibernate.User" table="t_user"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <set name="roles" table="t_user_role"> <key column="userid"/> <many-to-many class="com.bjsxt.hibernate.Role" column="roleid"/> </set> </class> </hibernate-mapping>