接第三部分内容,本章节就要简单多了。
市场是无情的,机遇和危机无处不在。张三在经历过生意红火之后,接下来的一年内生意场上连连告负,不得不把自己的摊子收缩一下。这第一件事要把跑运输的车卖掉,就是那辆牌照为“A00002”的。
package com.dao;
import java.util.*;
import net.sf.hibernate.*; import net.sf.hibernate.cfg.*;
import bo.*;
public class Test {
AutoInfo ai; People people; public void DoTest() { try { Configuration cfg = new Configuration().configure(); SessionFactory sessions = cfg.buildSessionFactory(); Session session = sessions.openSession(); Transaction tx = session.beginTransaction(); ai = (AutoInfo) session.find( "from AutoInfo where LICENSE_PLATE='A00002'").get( 0); people = ai.getOwnerNo(); people.getAutoInfoSet().remove(ai); session.delete(ai); tx.commit(); session.close(); } catch (Exception e) { System.out.println(e); } } }
|
为什么要从 People 对象中移除某个 AutoInfo 对象?
问得好!传统 JDBC 程序可以直接删除以“A00002”为条件查询出的记录,这样没有问题。但如果在 Hibernate 中用同样的方式直接删除,会引起不小的麻烦:
net.sf.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations): 2, of class: bo.AutoInfo |
造成无法删除的原因是PEOPLE 和 AUTO_INFO 表存在着一对多(one-to-many)关系,想要从 AUTO_INFO 删除一条记录,就必须用 people.getAutoInfoSet().remove(ai) 方法为 People 移除以“A00002”为条件查询出的AutoInfo 对象,才能真正删除该 AutoInfo 对象。
从张三的失落中回过头来,这次 Hibernate 之旅也即将结束了。最后要体验的是删除 PEOPLE 表及其关联的 AUTO_INFO 表。
package com.dao;
import java.util.*;
import net.sf.hibernate.*; import net.sf.hibernate.cfg.*;
import bo.*;
public class Test {
People people; public void DoTest() { try { Configuration cfg = new Configuration().configure(); SessionFactory sessions = cfg.buildSessionFactory(); Session session = sessions.openSession(); Transaction tx = session.beginTransaction(); people = (People) session.load(People.class,new Integer(1)); session.delete(people); tx.commit(); session.close(); } catch (Exception e) { System.out.println(e); } } } |
Hibernate 的优势又一次体现出来。我们只需把一对多(one-to-many)关系中“one”这方删除,与之相关联的所有其他记录会一并删除。
最后,通过这次旅程,也算把 Hibernate的特性体验了一把。作为一种 O/R Mapping 实现,它是很优秀的,希望我们都可以用好它。
(请注意!引用、转贴本文应注明原作者:Rosen Jiang 以及出处:http://blog.csdn.net/rosen) 
|