多對(duì)多其實(shí)是個(gè)很復(fù)雜的關(guān)系,,hibernate在進(jìn)行處理的時(shí)候借助中間表或者中間類。中間表是在映射文件的關(guān)聯(lián)標(biāo)簽(比如集合標(biāo)簽<set>)中由table屬性指定的由hibernate自動(dòng)生成的表,,它只有兩個(gè)字段,,分別由<key>和<many-to-many>標(biāo)簽的table屬性指定,作為外鍵分別用來(lái)指向關(guān)聯(lián)雙方表的主鍵,。中間類就是把我們的中間表抽象生成一個(gè)實(shí)體類,,在映射的時(shí)候分別和兩個(gè)關(guān)聯(lián)類構(gòu)成一對(duì)多的關(guān)系,即演變成兩個(gè)一對(duì)多來(lái)處理,。
我習(xí)慣使用中間表的方式,。
1.實(shí)體模型:
2.關(guān)系模型:
3.實(shí)體類:
Role.java
public class Role {
private Integer id; private String name; //一系列的setter.getter方法 @Override public String toString() { return "Role:" + name; } } Player.java
public class Player {
private Integer id; private String name; private Set<Role> roles; //一系列的setter.getter方法 @Override public String toString() { return "Player:" + name; } } 4.映射文件:
Role.hbm.xml
<class name="com.sxt.hibernate.many2many.entity.Role" table="sxt_hibernate_role">
<id name="id" length="4"> <generator class="native"></generator> </id> <property name="name" length="10"></property> </class> Player.hbm.xml
<class name="com.sxt.hibernate.many2many.entity.Player" table="sxt_hibernate_player">
<id name="id" length="4"> <generator class="native"></generator> </id> <property name="name" length="10"></property> <!--table="sxt_hibernate_user_role"含義,用來(lái)指定中間表 --> <set name="roles" table="sxt_hibernate_player_role" cascade="save-update"> <!--<key column="user_id">含義,指定中間表中用來(lái)指向本表的外鍵 --> <key column="player_id"></key> <!-- column含義,用來(lái)指定中間表中用來(lái)指向另一端表的外鍵 --> <many-to-many class="com.sxt.hibernate.many2many.entity.Role" column="role_id"></many-to-many> </set> </class> 5.hibernate配置文件:
參見(jiàn)上一篇。
6.測(cè)試方法:
public static void main(String[] args) {
Session session = HibernateUtils.getSession(); Transaction t = session.beginTransaction(); try { /** * 測(cè)試插入數(shù)據(jù) */ /* Role role1=new Role(); role1.setName("后衛(wèi)"); Role role2=new Role(); role2.setName("前鋒"); Role role3=new Role(); role3.setName("中鋒"); Player player1=new Player(); player1.setName("姚明"); Set<Role> roles1=new HashSet<Role>(); roles1.add(role3); player1.setRoles(roles1); Player player2=new Player(); player2.setName("詹姆斯"); Set<Role> roles2=new HashSet<Role>(); roles2.add(role1); roles2.add(role2); roles2.add(role3); player2.setRoles(roles2); //能正確保存.每保存player后,都要級(jí)聯(lián)保存它的role,并且級(jí)聯(lián)插入中間表記錄. session.save(player1); session.save(player2);*/ /** * 測(cè)試加載數(shù)據(jù) */ Player player=(Player)session.load(Player.class, 1); System.out.println(player); for(Iterator<Role> iterator=player.getRoles().iterator();iterator.hasNext();){ System.out.println(iterator.next()); } t.commit(); } catch (HibernateException e) { e.printStackTrace(); t.rollback(); } finally { HibernateUtils.closeSession(session); } } } |
|