java hibernate调用存储过程_java hibernate 调用oracle存储过程

本文介绍了如何在Java项目中使用Hibernate调用Oracle存储过程的两种方法。第一种方法直接通过Session创建SQLQuery,第二种方法是通过HibernateCallback自动管理事务,设置存储过程参数并执行。示例代码详细展示了调用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Session session =HibernateSessionFactory.getSession();

SQLQuery query = session.createSQLQuery("{Call Tj(?)}"); //这里调用存储过程

query.setString(1,"ddd");

List list =query.list();

session.close();

-------------------------------->项目中的方法一

public void updateBySP(final String callsql, final Object... pi) {

getHibernateTemplate().execute(new HibernateCallback() {

public Object doInHibernate(Session session)

throws HibernateException, SQLException {    -------->自动管理事务

Connection connection = session.connection();

CallableStatement cstmt = null;

try {

cstmt = connection.prepareCall(callsql);

cstmt.clearParameters();

if (pi != null) {    -------->参数判断及类型转换

for (int i = 0; i < pi.length; i++) {

if (pi[i] == null)

cstmt.setString(i + 1, null);

else {

if (pi[i] instanceof java.util.Date) {

cstmt.setDate(i + 1, new java.sql.Date(

((Date) pi[i]).getTime()));

} else if (pi[i] instanceof java.sql.Date) {

cstmt.setDate(i + 1, (java.sql.Date) pi[i]);

} else {

cstmt.setString(i + 1, pi[i].toString());

}

}

}

}

return cstmt.executeUpdate();

} finally {

if (cstmt != null)

cstmt.close();

if (connection != null) {

connection.close();

}

}

}

});

}

-------------------------------->项目中的方法二

public int executeBySQL(final String sql, final Object... args) {

if (sql == null) {

return 0;

}

Integer result = (Integer) getHibernateTemplate().execute(

new HibernateCallback() {

public Object doInHibernate(Session session)

throws HibernateException, SQLException {

SQLQuery sqlQuery = session.createSQLQuery(sql);

if (CollectionUtils.notEmpty(args)) {

for (int i = 0; i < args.length; i++) {

sqlQuery.setParameter(i, args[i]);

}

}

return sqlQuery.executeUpdate();

}

});

return result;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值