Java信徒

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  2 Posts :: 1 Stories :: 0 Comments :: 0 Trackbacks

深入浅出Hibernate P281讲到使用Hibernate3的Bulk delete/update方式删除记录时,写了段代码证明这种删除方式不能缓存同步,会从缓存中读取出数据库已经删除的信息,我依葫芦画瓢写了段代码,结果与书上结论相反,
请大家帮我看看到底怎么回事,我用的hibernate3.0,代码如下:



package mypack;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import sessionfactory.HibernateSessionFactory;

public class test2 {

 /**
  * @param args
  */


 public static void main(String[] args) {
  //储存插入记录的id
  int insertid;
  //新建实例
  TUser insertuser = new TUser();
  insertuser.setName("name1");
  insertuser.setResume("resume1");
  //插入实例
  Session session = HibernateSessionFactory.getSession();
  Transaction tx = session.beginTransaction();  
  session.save(insertuser);
  insertid = insertuser.getId();
  tx.commit();
  session.close();
  
  // 装载插入的实例
  session = HibernateSessionFactory.getSession();
  TUser user = (TUser) session.load(TUser.class, new Integer(insertid));
  System.out.println("装载实例成功,id==>" + user.getId());
  tx = session.beginTransaction();
  // 删除插入的实例
  String hql = "delete TUser where id = "+insertid;
  Query query = session.createQuery(hql);
  query.executeUpdate();
  tx.commit();
  // 读取删除的实例,抛出异常
  user = (TUser) session.load(TUser.class, new Integer(insertid));
  System.out.println("读取缓存中存放的id成功, id==>" + user.getId());
  // 捕捉异常
  try {
   System.out.println(user.getName());
  } catch (org.hibernate.ObjectNotFoundException e) {
   System.out.println("代码user.getname()发生异常,因为该实例已经被删除");
   System.out.println(e.toString());
   System.out.println("结论:Query.execxuteUpdate()方法删除数据是缓存同步的");
  }
  session.close();
 }
}


打印信息如下:

Hibernate: insert into tuser (name, resume) values (?, ?)
装载实例成功,id==>43
Hibernate: delete from tuser where id=43
读取缓存中存放的id成功, id==>43
Hibernate: select tuser0_.id as id0_, tuser0_.name as name0_0_, tuser0_.resume as resume0_0_ from tuser tuser0_ where tuser0_.id=?
代码user.getname()发生异常,因为该实例已经被删除
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [mypack.TUser#43]
结论:Query.execxuteUpdate()方法删除数据是缓存同步的
posted on 2007-01-16 18:18 庸世俗才 阅读(848) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: