论坛首页 入门技术论坛

hibernate 之M:N 配置方法

浏览 1378 次
该帖已经被评为新手帖
作者 正文
   发表时间:2011-02-27   最后修改:2011-02-27



public class Role implements Serializable {

private int rid ;

private String name;

private Set<Power> powers;

//get set 方法

}

Role.hbm.xml

<hibernate-mapping package="com.hw.dao">

<class name="Role" table="ROLE">

<id name="rid">

<column name="RID"></column>

</id>

<property name="name">

<column name="NAME"></column>

</property>

<set name="powers" table="ROLE_POWER" cascade="all">

<key>

<column name="RID"></column>

</key>

<many-to-many class="Power">

<column name="lid"></column>

</many-to-many>

</set>

</class>

</hibernate-mapping>  


Power.java 文件

public class Power implements Serializable {

private int lid;

private String name;

private Set<Role> roles;

//getset方法

}

Power.hbm.xml

<hibernate-mapping package="com.hw.dao">

<class name="Power">

<id name="lid" column="LID"></id>

<property name="name" column="NAME"></property>

<set name="roles" table="ROLE_POWER" cascade="all">

<key>

<column name="lid"></column>

</key>

<many-to-many class="Role">

<column name="rid"></column>

</many-to-many>

</set>

</class>

</hibernate-mapping>        

测试类

package com.hw.dao;


import java.util.HashSet;

import java.util.List;

import java.util.Set;


import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;


public class test {

public static void main(String[] args) {

Configuration conf = new Configuration().configure();

SessionFactory sf= conf.buildSessionFactory();

Session s= sf.openSession();


s.beginTransaction();

Role role= new Role();

role.setRid(1);

role.setName("admins");

Set<Power> powerset= new HashSet<Power>();

Power poser = new Power();

poser.setLid(1);

poser.setName("adds1");

powerset.add(poser);


role.setPowers(powerset);

System.out.println(role.getRid()+role.getName());

s.save(role);

s.getTransaction().commit(); 

// String hql="from Role";

// Query query = s.createQuery(hql);

// List<Role> list = query.list();

// for (Role role : list) {

// System.out.println(role.getRid()+" "+role.getName());

// Set<Power> power =role.getPowers();  

// for (Power power2 : power) {

// System.out.println(power2.getLid()+" "+power2.getName());

// }

// }

}

}

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics