Hibernate many to many 配置

和onetoone一样,首先写了两个实体类

Course(

privateintcou_id;

privateStringcou_name;)和

Student(

privateintstu_id;

privateStringstu_name;

privateSet<Course>courses;)生成get,set方法,

然后配置实体类的映射文件Course.hbm.xml和Student.hbm.xml

代码:

----------Course.hbm.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD

3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"

>

<hibernate-mapping>

<classname="cn.hdu.entity.Course"table="COURSE">

<idname="cou_id"column="COU_ID">

<generatorclass="sequence"><param

name="sequence">COU_sequences</param></generator>

</id>

<propertyname="cou_name"column="COU_NAME"></property>

<setname="students"cascade="save-update"lazy="false"

table="STUDENT_COURSE">

<keycolumn="COU_ID"></key>

<many-to-manyclass="cn.hdu.entity.Student"column="STU_ID"></many-to

-many>

</set>

</class>

</hibernate-mapping>

-----------Student.hbm.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD

3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"

>

<hibernate-mapping>

<classname="cn.hdu.entity.Student"table="STUDENT">

<idname="stu_id"column="STU_ID">

<generatorclass="sequence"><param

name="sequence">STU_SEQUENCES</param></generator>

</id>

<propertyname="stu_name"column="STU_NAME"></property>

<setname="courses"cascade="save-update"lazy="false"

table="STUDENT_COURSE">

<keycolumn="STU_ID"></key>

<many-to-manyclass="cn.hdu.entity.Course"column="COU_ID"></many-to-

many>

</set>

</class>

</hibernate-mapping>

注意:属性的解释大多同于onetoone例子(详见Hibernateonetoone配置

),这里多对对的情况采用中间表的形式,也就是说数据库中要建立第三张表

table="STUDENT_COURSE",存储STU_ID和COU_ID字段;manytomany属性使得

STU_ID和COU_ID分别对应表中多条记录,也就是一门课程有多个学生,一个学

生有多门课程。

做完映射之后同样不要忘记把映射文件写入hibernate.cfg.xml;

代码:

<session-factory>

.........

<propertyname="show_sql">TRUE</property>

<mappingresource="cn/hdu/entity/Student.hbm.xml"/>

<mappingresource="cn/hdu/entity/Course.hbm.xml"/>

</session-factory>

写一个实现类

publicclassServiceImp{

publicList<Course>getCourseAll(){

Sessionsession=HibernateSessionFactory.getSession();

Queryquery=session.createQuery("fromCourse");

List<Course>list=query.list();

HibernateSessionFactory.closeSession();

returnlist;

}

}

测试类:

publicclassTest{

publicstaticvoidmain(String[]args){

ServiceImpservice=newServiceImp();

List<Course>list=service.getCourseAll();

for(Coursecc:list)

{System.out.println("课程名字:");

System.out.println(cc.getCou_name());

}

看下查询后输出结果。

相关推荐