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 application cannot update/delete data and is using SQL Server.
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.
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.
Here is the stored procedure:
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
Update:
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();
Things I have noticed:
- Parameter names didn't work for me, so try using parameter index.
- Correct sql statement
{call sp_name(?,?)}
instead ofcall sp_name(?,?)
- If stored procedure is returning a result set, even if you know with only one row,
getSingleResult
wont work - Pass a
resultSetMapping
name or result class details
JPA 2.0 doesn't support RETURN values, only calls.
My solution was. Create a FUNCTION calling PROCEDURE.
So, inside JAVA code you execute a NATIVE QUERY calling the oracle FUNCTION.
This answer might be helpful if you have entity manager
I had a stored procedure to create next number and on server side I have seam framework.
Client side
Database Side (SQL server) I have stored procedure named
getNextNmber
Try this code:
You can use
@Query(value = "{call PROC_TEST()}", nativeQuery = true)
in your repository. This worked for me.Attention: use '{' and '}' or else it will not work.
JPA 2.1 now support Stored Procedure, read the Java doc here.
Example:
See detailed example here.
persistence.xml
codigo java