1、使用对象更新
public void updateImagePath(Weibo weibo){ Session session = HibernateUtil.currentSession(); try { Transaction tx = session.beginTransaction(); session.update(weibo); tx.commit(); } catch (Exception e) { // TODO: handle exception System.err.println("search failed!!!!!!"); }finally{ HibernateUtil.closeSession(); HibernateUtil.sessionFactory.close(); } }
2、使用sql语句更新
public int updateImagePath1(String imagePath, String weiboId){ Session session = HibernateUtil.currentSession(); try { String sql = "update t_weiboo set imagePath='"+imagePath+"' where weiboId='M_Boj1Wc4xC';"; Transaction tx = session.beginTransaction(); Query query = session.createSQLQuery(sql); int state= query.executeUpdate(); tx.commit(); if(state==1) System.out.println("修改路径成功!"); return state; } catch (Exception e) { // TODO: handle exception System.err.println("search failed!!!!!!"); }finally{ HibernateUtil.closeSession(); HibernateUtil.sessionFactory.close(); } return 0; }
3、先通过id获取对象,再更新
public void update1() { Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); Weibo wb = (Weibo) session.get(Weibo.class, 3); wb.setImagePath(""); session.update(wb); tx.commit(); }