轉自:https://blog.csdn.net/angus_17/article/details/8501668
1.
這兩個方法都是為了Spring在接管Hibernate之后,可以對HibernateDaoSupport進行靈活的擴展而用的。
二者的主要區別在于,execute返回的是一個Object,而executeFind方法返回的是一個List.
//使用executeFind
protected void deleteByVehicleId(final int vehicleId) throws Exception {
?try {
?this.getHibernateTemplate().executeFind(
?new HibernateCallback() {
?public Object doInHibernate(Session session) throws HibernateException, SQLException {
?Query q = session.createQuery("delete from Vehicle v where v.id=" + vehicleId );
?q.executeUpdate();
?return null;
?}
?});
?} catch (Exception e) {
?throw e;
?}
}
//使用execute
public String updateScreen(final int screenId,final String configStr){
Object o = getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
SQLQuery query = session.createSQLQuery("update HPS_ParkingLotScreen ?set config_Str='" + configStr + "' where id=" +screenId);
try{
int ii = query.executeUpdate();
System.out.println(ii);
return "success";
}catch (Exception e) {
e.printStackTrace();
}
return "fail";
}
});
return o.toString();
}
另外,在new HibernateCallback的內部類的doInHibernate方法中,它的返回值,就是execute或executeFind方法的返回值。