读书人

Hibernate many to many 配备

发布时间: 2012-08-31 12:55:03 作者: rapoo

Hibernate many to many 配置

和one to one 一样,首先写了两个实体类
Course (
private int cou_id;
private String cou_name;)和
Student (
private int stu_id;
private String stu_name;
private Set<Course> courses;)生成get,set方法,
然后配置实体类的映射文件Course.hbm.xml和Student.hbm.xml
代码:
----------Course.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD

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

>
<hibernate-mapping>
<class name="cn.hdu.entity.Course" table="COURSE">
<id name="cou_id" column="COU_ID">

<generator column="COU_NAME"></property>


<set name="students" cascade="save-update" lazy="false"

table="STUDENT_COURSE">
<key column="COU_ID"></key>
<many-to-many column="STU_ID"></many-to

-many>
</set>
</class>

</hibernate-mapping>

-----------Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD

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

>
<hibernate-mapping>
<class name="cn.hdu.entity.Student" table="STUDENT">
<id name="stu_id" column="STU_ID">

<generator column="STU_NAME"></property>


<set name="courses" cascade="save-update" lazy="false"

table="STUDENT_COURSE">
<key column="STU_ID"></key>
<many-to-many column="COU_ID"></many-to-

many>
</set>
</class>

</hibernate-mapping>


注意:属性的解释大多同于 one to one例子(详见Hibernate one to one配置

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

table="STUDENT_COURSE",存储STU_ID和COU_ID字段;many to many属性使得
STU_ID和COU_ID分别对应表中多条记录,也就是一门课程有多个学生,一个学
生有多门课程。
做完映射之后同样不要忘记把映射文件写入hibernate.cfg.xml;
代码:
<session-factory>
.........
<property name="show_sql">TRUE</property>
<mapping resource="cn/hdu/entity/Student.hbm.xml" />
<mapping resource="cn/hdu/entity/Course.hbm.xml" />
</session-factory>


写一个实现类
public class ServiceImp {

public List<Course> getCourseAll() {
Session session=HibernateSessionFactory.getSession();
Queryquery=session.createQuery("from Course");
List<Course> list=query.list();
HibernateSessionFactory.closeSession();
return list;
}
}
测试类:
public class Test{
public static void main(String[] args) {
ServiceImp service = new ServiceImp();
List<Course> list=service.getCourseAll();
for(Course cc:list)
{System.out.println("课程名字:");

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

}


看下查询后输出结果。

读书人网 >软件架构设计

热点推荐