【问题标题】:how to execute the stored procedure in hibernate 3如何在hibernate 3中执行存储过程
【发布时间】:2012-07-09 12:35:34
【问题描述】:

我是休眠的新手。我在我的应用程序中使用hibernate annotations 使用hibernate 3,我正在用struts 1.3 开发应用程序。

我的问题是: 我用谷歌搜索了很多,但不明白如何在 hibernate using annotations 中调用存储过程,我有一个简单的场景:假设我的 jsp 中有 2 个字段,比如 1) 代码 2) 名称,我已经在数据库中创建了一个存储过程,用于将这些记录插入表中。现在我的问题是如何执行它

 List<MyBean> list = sessionFactory.getCurrentSession()
                          .getNamedQuery("mySp")
                        .setParameter("code", code)
                        .setParameter("name", name)

我不知道如何执行此操作的确切代码。但我想类似的事情实际上我来自 jdbc 背景,因此不知道如何执行此操作,并且在使用存储过程选择数据库中的数据时我想要同样的事情。

【问题讨论】:

    标签: java hibernate stored-procedures


    【解决方案1】:

    Hibernate 提供了许多简单的方法来调用类似 SP 的方法

    1. 本机 SQL
    2. 本机 SQL 中的命名查询作为注释/XML 映射文件

    以下链接显示了如何实现上述每一项

    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

    使用休眠运行本机 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);
    

    【讨论】:

    • 您可以通过谷歌搜索找到几个关键字的链接。如果你能提供一些代码示例就更好了。
    【解决方案2】:

    您可以使用 Hibernate 的 SQLQuery 执行您的存储过程,使用与您针对数据库调用它时相同的 SQL。例如,在 postgreSQL 中:

    String query = "select schema.procedure_name(:param1)";
    SQLQuery sqlquery = sessionFactory.getCurrentSession().createSQLQuery(query);
    sqlquery.setInteger("param1", "this is first parameter");
    sqlQuery.list();
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 2016-04-13
      • 2019-06-23
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多