如何在hibernate2中执行这样一条UPDATE语句

2025-02-28 15:22:12
推荐回答(5个)
回答1:

给你一个我写的方法参考一下:
public void updateClientState() {
try {
getHibernateTemplate().execute(new HibernateCallback(){

Date currentTime = new Date();//当前系统时间
Date day180 = DateUtil.getAddDay(currentTime, -180);//当前系统时间30 天以前的时间
Date day90 = DateUtil.getAddDay(currentTime, -90);//当前系统时间30 天以前的时间

SimpleDateFormat sdftime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// 更新所有在90天以内有合同记录或者创建时间是在90天以内
String before90day = "update t_sme_sps_client set client_state = ?"+
"where client_contract_date >= ? "+
"and (client_parent_id is null)";
// 更新所有在90天到180天之间的有合同记录或者创建时间是在90天到180天之间的
String before180day = "update t_sme_sps_client set client_state = ?" +
"where (client_contract_date< ? and client_contract_date >= ?)" +
"and (client_parent_id is null)";

String hqlothers = "update t_sme_sps_client set client_state = ? " +
"where client_contract_date < ? " +
"and (client_parent_id is null) ";
// 更新所有在180天以外的
public Object doInHibernate(Session session)
throws HibernateException, SQLException {

Connection conn=session.connection();

PreparedStatement ps = conn.prepareStatement(before90day);
ps.setInt(1,0);
ps.setTimestamp(2, Timestamp.valueOf(sdftime.format(day90)));
ps.executeUpdate();

PreparedStatement ps2 = conn.prepareStatement(before180day);
ps2.setInt(1,1);
ps2.setTimestamp(2, Timestamp.valueOf(sdftime.format(day90)));
ps2.setTimestamp(3, Timestamp.valueOf(sdftime.format(day180)));
ps2.executeUpdate();

PreparedStatement ps3 = conn.prepareStatement(hqlothers);
ps3.setInt(1,2);
ps3.setTimestamp(2, Timestamp.valueOf(sdftime.format(day180)));
ps3.executeUpdate();

conn.commit();

return null;
}});
} catch (DataAccessException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (ParseException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}

}

回答2:

hibernate2不行吧,建议你还是看看hibernate3吧,不要浪费时间呀,hibernate3是可以的,它提供DML式的HQL语句,可执行update、delete形式的语句,是executeUpdate()方法。

回答3:

HIBERNATE是面向对象的框架,HQL语句里面不能识别UPDATE关键字,只有UPDATE方法,在方法里传递你要更新的对象就行了。

回答4:

把你的程序改一下:
String sql ="update TABLE=:TABLE set content=replace(content,'OLD=:OLD','NEW=:NEW')";
Transaction tx = session.beginTransaction();
try{
Query query = session.createQuery(sql);
query.setString("TABLE", type);
query.setString("OLD", old);
query.setString("NEW", myNew);
query.executeUpdate();
tx.commit();
}catch (Exception e)
{

}

回答5:

query.list()是一个查询的方法 也就是说把结果变为list
而更新是要调用query.executeUpdate()