<one-to-many/>一对多:查询班级的同时查询所有学生信息
tGroup
public class tGroup implements Serializable{
private Long id;
private String name;
private Set uses = new HashSet();
//省略GET/SET
}
tUser
public class tUser implements Serializable{
private Long id;
private String name;
private tGroup tgr
//省略GET/SET
}
tGroup.hbm.xml
<set name="uses" lazy="false" inverse="true" cascade="all"> —— tGroup类中user集合 / 取消延迟加载
<key column="group_Id"></key>—— tUser表中的对应外键
<one-to-many class="com.hibtest2.entity.tUser"/>—— tUser类名
</set>
<hibernate-mapping>
<class name="com.hibtest2.entity.tGroup" table="t_group">
<id name="id" type="java.lang.Long">
<column name="ID" precision="22" scale="0" />
<generator class="sequence">
<param name="sequence">seq_emp</param>
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="50"></column>
</property>
<set name="uses" lazy="false" inverse="true" cascade="all">
<key column="group_Id"></key>
<one-to-many class="com.hibtest2.entity.tUser"/>
</set>
</class>
</hibernate-mapping>
tUser.hbm.xml
<hibernate-mapping>
<class name="com.hibtest2.entity.tUser" table="t_user">
<id name="id" type="java.lang.Long">
<column name="ID" precision="22" scale="0" />
<generator class="sequence">
<param name="sequence">seq_emp</param>
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="50"></column>
</property>
<many-to-one name="tgr" column="group_Id" class="com.hibtest2.entity.tGroup" cascade="all"></many-to-one>
</class>
</hibernate-mapping>
test1新增:新tGroup和新tUser
session = sf.openSession();
session.beginTransaction();
tGroup tg = new tGroup();
tg.setName("JSP");
Set set = new HashSet();
for(int i = 0;i < 3;i++){
tUser tu = new tUser();
tu.setName("a"+i);
tu.setTgr(tg);
set.add(tu);
}
tg.setUses(set);
session.save(tg);
session.getTransaction().commit();
session.close();
新增:新tGroup对应老tUser
session = sf.openSession();
session.beginTransaction();
tGroup tg = new tGroup();
tg.setName("C");
Set set = new HashSet();
tUser tu1 = (tUser) session.get(tUser.class, Long.parseLong("35"));
tu1.setTgr(tg);
tUser tu2 = (tUser) session.get(tUser.class, Long.parseLong("36"));
tu2.setTgr(tg);
set.add(tu1);
set.add(tu2);
tg.setUses(set);
session.saveOrUpdate(tg);
session.getTransaction().commit();
session.close();
查询:查看某一Group信息及其所有学生( one - more 的意义)
//查看班级的时候,可能所有学生的信息 —— on - to - many
session = sf.openSession();
tGroup t = (tGroup) session.get(tGroup.class, Long.parseLong("24"));
System.out.println("组名:"+t.getName());
Iterator it = t.getUses().iterator();
while(it.hasNext()){
tUser tt = (tUser) it.next();
System.out.println(tt.getName());
}