从Java / JPA调用存储过程 [英] Calling stored procedure from Java / JPA

查看:868
本文介绍了从Java / JPA调用存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的Web应用程序来调用存储过程并检索一些数据。
它是一个非常简单的应用程序,它与客户端的数据库进行交互。我们传递员工ID和公司ID,存储过程将返回员工详细信息。

I am writing a simple web application to call a stored procedure and retrieve some data. Its a very simple application, which interacts with client's database. We pass employee id and company id and the stored procedure will return employee details.

Web应用程序无法更新/删除数据并且正在使用SQL Server。

Web application cannot update/delete data and is using SQL Server.

我正在Jboss AS中部署我的Web应用程序。我应该使用JPA来访问存储过程还是 CallableStatement 。在这种情况下使用JPA的任何优点。

I am deploying my web application in Jboss AS. Should I use JPA to access the stored procedure or CallableStatement. Any advantage of using JPA in this case.

此外,调用此存储过程的sql语句是什么。我之前从未使用过存储过程,而且我正在努力解决这个问题。谷歌没有多大帮助。

Also what will be the sql statement to call this stored procedure. I have never used stored procedures before and I am struggling with this one. Google was not much of a help.

这是存储过程:

CREATE procedure getEmployeeDetails (@employeeId int, @companyId int)
as
begin
    select firstName, 
           lastName, 
           gender, 
           address
      from employee et
     where et.employeeId = @employeeId
       and et.companyId = @companyId
end

更新:

对于使用 JPA 调用存储过程有问题的其他人。

For anyone else having problem calling stored procedure using JPA.

Query query = em.createNativeQuery("{call getEmployeeDetails(?,?)}",
                                   EmployeeDetails.class)           
                                   .setParameter(1, employeeId)
                                   .setParameter(2, companyId);

List<EmployeeDetails> result = query.getResultList();

我注意到的事情:


  1. 参数名称对我不起作用,所以请尝试使用参数索引。

  2. 更正sql语句 {call sp_name(?,?)} 而不是调用sp_name(?,?)

  3. 如果存储过程返回结果集,甚至如果您只知道一行, getSingleResult 将无法正常工作

  4. 传递 resultSetMapping 名称或结果类详细信息

  1. Parameter names didn't work for me, so try using parameter index.
  2. Correct sql statement {call sp_name(?,?)} instead of call sp_name(?,?)
  3. If stored procedure is returning a result set, even if you know with only one row, getSingleResult wont work
  4. Pass a resultSetMapping name or result class details


推荐答案

JPA 2.1现在支持存储过程,请阅读Java doc 此处

JPA 2.1 now support Stored Procedure, read the Java doc here.

示例:

StoredProcedureQuery storedProcedure = em.createStoredProcedureQuery("sales_tax");
// set parameters
storedProcedure.registerStoredProcedureParameter("subtotal", Double.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("tax", Double.class, ParameterMode.OUT);
storedProcedure.setParameter("subtotal", 1f);
// execute SP
storedProcedure.execute();
// get result
Double tax = (Double)storedProcedure.getOutputParameterValue("tax");

查看详细示例这里

这篇关于从Java / JPA调用存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆