TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
1,对于多方(不需要更改xml文件):
<class name="com.zhangjie.hib.entity.onetomany.Jd" table="TBL_JD" schema="dbo" catalog="zf">
<id name="jdid" type="java.lang.Integer">
<column name="jdid" />
<generator class="native"></generator>
</id>
<property name="jd" type="java.lang.String">
<column name="jd" length="50" />
</property>
<property name="qxid" type="java.lang.Integer">
<column name="qxid" />
</property>
</class>
2,对于一方:
更改Qx.java:
增加属性:private Set<Jd> jds = new HashSet<Jd>();
更改XML:
<set name="jds" cascade="save-update" lazy="false" inverse="true">
<key column="qxid"/>
<one-to-many class="com.zhangjie.hib.entity.onetomany.Jd"/>
</set>
cascade:save-update级联保存和更新;
lazy:false自动级联查询;
inverse:true由多的一方来维护关系
3,级联查询代码:
Session session = HibernateSessionFactory.getSession();
Qx qx = (Qx)session.get(Qx.class, 1);
System.out.println("区县:"+qx.getQx());
//实行级联查询
//qx.getJds().iterator();
session.close();
Set<Jd> jds = qx.getJds();
for(Jd jd : jds){
System.out.println("街道:"+jd.getJd());
}
4,级联保存代码:
Session session = HibernateSessionFactory.getSession();
Qx qx = new Qx();
qx.setQx("平江县");
Jd jd1 = new Jd();
jd1.setJd("长寿镇");
Jd jd2 = new Jd();
jd2.setJd("嘉义镇");
Jd jd3 = new Jd();
jd3.setJd("向家镇");
Set<Jd> jds = new HashSet<Jd>();
jds.add(jd1);
jds.add(jd2);
jds.add(jd3);
qx.setJds(jds); //建立qx与jd的一对多的关系
//建立事务
Transaction tx = session.beginTransaction();
session.save(qx);
tx.commit();
session.close();
|
|