数据库:
--学生表
create table stu
(
s_id int identity(1,1) not null primary key,
s_name varchar(50),
s_sex varchar(20)
)
Go
--科目表
create table subject
(
b_id int identity(1,1) not null primary key,
b_name varchar(50)
)
--中间关系表
create table stu_sub
(
t_id int identity(1,1) not null primary key,
s_id int,
b_id int
)
Stu.hbm.xml配置:
<hibernate-mapping>
<class name="com.mengya.entity.Stu" table="stu" schema="dbo" catalog="mp">
<id name="SId" type="java.lang.Integer">
<column name="s_id" />
<generator class="native" />
</id>
<property name="SName" type="java.lang.String">
<column name="s_name" length="50" />
</property>
<property name="SSex" type="java.lang.String">
<column name="s_sex" length="20" />
</property>
<!-- 集合名称为:subject,关系表为:stu_sub -->
<set name="subject" table="stu_sub" inverse="false" cascade="save-update">
<!-- 在多对多中的关系表中的s_id找到本对象 -->
<key>
<column name="s_id"></column>
</key>
<!-- 集合中放的对象是com.mengya.entity.Subject -->
<many-to-many class="com.mengya.entity.Subject">
<!-- 在多对多中的关系表中的b_id找到com.mengya.entity.Subject对象 -->
<column name="b_id"></column>
</many-to-many>
</set>
</class>
</hibernate-mapping>
Subject.hbm.xml配置:
<hibernate-mapping>
<class name="com.mengya.entity.Subject" table="subject" schema="dbo"
catalog="mp">
<id name="BId" type="java.lang.Integer">
<column name="b_id" />
<generator class="native" />
</id>
<property name="BName" type="java.lang.String">
<column name="b_name" length="50" />
</property>
<!-- 集合名称为:stu,关系表为:stu_sub -->
<set name="stu" table="stu_sub">
<!-- 在多对多中的关系表中的b_id找到本对象 -->
<key>
<column name="b_id"></column>
</key>
<many-to-many class="com.mengya.entity.Stu">
<!-- 在多对多中的关系表中的s_id找到com.mengya.entity.Stu对象 -->
<column name="s_id"></column>
</many-to-many>
</set>
</class>
</hibernate-mapping>
测试:
public void save() {
Stu stu1 = new Stu();
Stu stu2 = new Stu();
Subject sub1 = new Subject();
Subject sub2 = new Subject();
stu1.setSName("张明学");
stu1.setSSex("男");
stu2.setSName("张丹凤");
stu2.setSSex("女");
sub1.setBName("Java");
sub2.setBName(".NET");
/*
* 这样添加是不对的,因为我在Stu.hbm.xml中配置是:inverse="false" cascade="save-update"
* 表示stu对象对stu对象中的set集合里的对象,维护关联关系,并保持save-update操作
*/
// sub1.getStu().add(stu1);
// sub1.getStu().add(stu2);
//
// sub2.getStu().add(stu1);
// sub2.getStu().add(stu2);
/*
* 故:stu对象集合中应封装sub对象
*/
stu1.getSubject().add(sub1);
stu1.getSubject().add(sub2);
stu2.getSubject().add(sub2);
/*
* 在上面添加中,我们仅仅让学生维护了关系,即学生知道科目,科目不知道学习
* 其实多对多中,只要让一方维护关系就可以了。多对多的关系维据中向中间表中插入数据,
* 若双方都维护关系就中间表中的数据就有重复的了.
*/
session=this.GetSession();
tran=session.beginTransaction();
session.save(stu1);
session.save(stu2);
tran.commit();
session.close();
}
个人说明:多对多的查询效率很低,它会去查三张表,若数据量大的话,效率很低.所以数据量大的话不适合建立多对多的关系.