hibernate调用存储过程

/**
	 * 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 "执行成功";
	}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值