hibernate更新数据方法小结

复制代码 代码如下:

  Usertable user=null;

  Session session=HibernateSessionFactory.getSession();

  String sql="from Usertable as user where user.username=?";

  Query q=session.createQuery(sql);

  q.setString(0,username);

  List l=q.list();

  Iterator ite=l.iterator();

  if(ite.hasNext()){

  user=(Usertable)ite.next();

  }

  return user;

  查询完以后才能更新用SESSION.UPDATE就行了。

  Hibernate的session接口的update()方法可以更新持久化对象.使其对象属性的状态改变传递到数据库.

  

复制代码 代码如下:

  public boolean updateNews(Devinfo df) throws HibernateException{

  net.sf.hibernate.Session sess =HibernateUtil.currentSession();

  Transaction tx = sess.beginTransaction();

  try{

  Devinfo d=new Devinfo();

  sess.load(d,df.getNewsid());

  d.setTypeId(df.getTypeId());

  d.setSubject(df.getSubject());

  d.setContent(df.getContent());

  d.setMdate(new Date((new java.util.Date()).getTime()).toString());

  sess.update(d);

  tx.commit();

  HibernateUtil.closeSession();

  return true;

  }

  catch(HibernateException e){

  e.printStackTrace();

  return false;

  }

  }