java 如何在hibernate 3中执行存储过程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11395123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to execute the stored procedure in hibernate 3
提问by ZohebSiddiqui
I am new in hibernate. I am using hibernate 3 in my application using hibernate annotations , I am developing application in struts 1.3.
我是休眠的新手。我正在使用 hibernate annotations 在我的应用程序中使用 hibernate 3,我正在 struts 1.3 中开发应用程序。
My question is : I have googled a lot but could not understand how to call a stored procedure in hibernate using annotations, I have a simple scenario : suppose I have 2 fields in my jsp say 1) code 2) name , I have created a stored procedure in database for inserting those records into table. Now my problem is that how to execute it
我的问题是:我在谷歌上搜索了很多,但无法理解如何使用注释在休眠中调用存储过程,我有一个简单的场景:假设我的 jsp 中有 2 个字段,比如 1) 代码 2) 名称,我创建了一个数据库中的存储过程,用于将这些记录插入表中。现在我的问题是如何执行它
List<MyBean> list = sessionFactory.getCurrentSession()
.getNamedQuery("mySp")
.setParameter("code", code)
.setParameter("name", name)
I don't know the exact code how to do this. But I guess something like that actually I come from jdbc background therefore have no idea how to do this and same thing I want when selectingthe data from database using stored procedure.
我不知道如何做到这一点的确切代码。但我想类似的事情实际上我来自 jdbc 背景,因此不知道如何做到这一点,并且在使用存储过程从数据库中选择数据时我想要做同样的事情。
回答by Vaibhav Fouzdar
Hibernate provides many simple ways to call a SP like
Hibernate 提供了许多简单的方法来调用 SP,例如
- Native SQL
- Named Query in native SQL as Annotation/XML mapping file
- 本机 SQL
- 本机 SQL 中的命名查询作为注释/XML 映射文件
Following link shows how each of above can be implemented
以下链接显示了如何实现上述每一项
http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/
http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html#sp_query
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html#sp_query
Sample to run native SQL query using hibernate:
使用休眠运行本机 SQL 查询的示例:
Session session = getSession();
SQLQuery sqlQuery = session.createSQLQuery("SELECT COUNT(id) FROM tableName WHERE external_id = :external_id");
sqlQuery.setParameter("external_id", idValue);
int count = ((BigInteger) sqlQuery.uniqueResult()).intValue();
releaseSession(session);
回答by jelies
You can execute your stored procedure using Hibernate's SQLQuery with the same SQL as when you call it against the database. For example, in postgreSQL:
您可以使用 Hibernate 的 SQLQuery 执行存储过程,其 SQL 与针对数据库调用它时的 SQL 相同。例如,在 postgreSQL 中:
String query = "select schema.procedure_name(:param1)";
SQLQuery sqlquery = sessionFactory.getCurrentSession().createSQLQuery(query);
sqlquery.setInteger("param1", "this is first parameter");
sqlQuery.list();
Hope it helps.
希望能帮助到你。