/**
* hibernate调用存储过程
*
* @param name
* hibernate中定义的存储过程名字
* @param obj
* 存储过程所对应的参数
* @return 集合对象
*/
public List<?> collect(String name, Object[] obj) throws Exception {
final String procedure = name;
final Object[] fobj = obj;
List<?> list = (List<?>) this.getDaoToolHibernateTemplate().execute(
new HibernateCallback() {
public List<?> doInHibernate(Session session)
throws HibernateException {
List<?> list1 = null;
try {
Query query = session.getNamedQuery(procedure);
if (fobj.length > 0) {
for (int i = 0; i < fobj.length; i++) {
query.setParameter(i, fobj[i]);
}
}
list1 = query.list();
session.flush();
} catch (Exception e) {
log.debug("调用存储过程“" + procedure + "”出错");
e.printStackTrace();
}
return list1;
}
});
return list;
}
/**
* 直接执行无返回结果集的存储过程
*
* @param name
* 存储过程名称
* @param obj
* 过程参数
*/
@SuppressWarnings("deprecation")
public String collectNoResult(String name, Object[] obj) throws Exception {
final String fname = name;
final Object[] fobj = obj;
StringBuffer procedureTemp = new StringBuffer("{call " + fname + "(");
if (fobj.length > 0) {
for (int i = 0; i < fobj.length; i++) {
if (i == 0) {
procedureTemp.append("?");
} else {
procedureTemp.append(",?");
}
if (i == fobj.length - 1) {
procedureTemp.append(")}");
}
}
} else {
procedureTemp.append(")}");
}
final String procedure = procedureTemp.toString();
this.getDaoToolHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
Transaction tx = session.beginTransaction();
Connection con = session.connection();
CallableStatement cstmt;
try {
cstmt = con.prepareCall(procedure);
if (fobj.length > 0) {
for (int i = 0; i < fobj.length; i++) {
cstmt.setObject(i + 1, fobj[i] == null ? null
: fobj[i].toString());
}
}
cstmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
tx.commit();
return "执行成功";
}
}, true);
return "执行成功";
}
hibernate调用存储过程
最新推荐文章于 2024-09-14 18:46:05 发布