1 我这里以书本表和类别表为例 一定义好桥接表,分别是书本,类别表的外键 session.get(Book.class,1)-> select*from t_hibernate_book where book_id=?(1) resultSet-> 1 西游记 50 Book b=Class.forName(“com.zking.hibernate.entity.Book”).newInstance(); 通过反射实例化赋值
hibernate 处理关联关系 通过set找到桥接表(table属性),找到当前实体类对应表的主键在桥接表的外键(key标签的column属性) select*from t_hibernate_book_category bid=1; resultSet cid 1,2 然后通过set标签(many-to-many column 得到(关联表的主键在t_hibernate_book_category的外键(cid)) 通过 class得到表名(t_hibernate_category)) select * from t_hibernate_book_category t_hibernate_category inner join t_hibernate_category t_hibernate_category on t_hibernate_category.cid=t_hibernate_category.category_id where t_hibernate_category.bid=? 也就是内连接得到结果集 通过反射类似于EntityBaseDao->list<category> 在将值保存到set集合中3 相关配置 Book.hbm.xml
<set name="categories" table="t_hibernate_book_category" cascade="save-update" inverse="true" > <!-- 配置外键字段 --> <key column="bid"></key> <!-- 配置外键关联的表(类) --> <many-to-many column="cid" class="com.zking.hibernate.entity.Category"/> </set>Category.hbm.xml
<set name="books" table="t_hibernate_book_category" cascade="save-update" inverse="true"> <!-- 配置外键字段 --> <key column="cid"></key> <!-- 配置外键关联的表(类) --> <many-to-many column="bid" class="com.zking.hibernate.entity.Book"/> </set>