简体   繁体   中英

How to call ms sql store procedure using hibernate 4.0

i am working with store procedure ie

CREATE PROCEDURE test 
(
@INPUTPARAM INT,
@OUTPUTPARAM VARCHAR(20)
)
AS
SELECT @OUTPUTPARAM=S.NAME+','+D.NAME
FROM STUDENT S,DEPARTMENT D
WHERE S.DEPTID=D.DEPARTID AND D.DEPARTID=@INPUTPARAM
BEGIN
END

how to get out parameter from java class using hibernate please share code example

CREATE PROCEDURE test 
(
@INPUTPARAM INT,
@OUTPUTPARAM VARCHAR(20) OUTPUT --<-- You need to use key word "OUTPUT" here
)
AS
BEGIN

  SELECT @OUTPUTPARAM = S.NAME + ',' + D.NAME
  FROM  STUDENT S INNER JOIN DEPARTMENT D
  ON    S.DEPTID = D.DEPARTID         --<-- Use New Syntax of join with On Clause
  WHERE D.DEPARTID = @INPUTPARAM

END

EXECUTE Procedure

DECLARE @Var VARCHAR(20);
EXECUTE dbo.test 
@INPUTPARAM = 1
@OUTPUTPARAM = @Var OUTPUT --<-- use OUTPUT key word here as well

SELECT  @Var

The only way to do it is using em.createNativeQuery and talk directly with you DB Server in SQL.

Update:

Here is, how it could be done:

//get connection from em
Session session = (Session)em.getDelegate();
Connection conn = session.connection();

//Native SQL
final CallableStatement callStmt = conn.prepareCall("{call your.function(?)}");
callStmt.setLong(1, documentId);
callStmt.execute();

if (callStmt.getMoreResults()) {
   ResultSet resSet = cStmt.getResultSet();
   //Do something good with you result
   resSet.close();
}
callStmt.close();

//Don't know if calling conn.close(); is a good idea. Since the session owns it.

Hope that helps a little.

Notes:

If you are using JPA 2.0, you can get the session using

Connection conn = em.unwrap(Session.class).connection();

If you are using JPA 2.1, you can call stored procedures directly

 StoredProcedureQuery query = em.createNamedStoredProcedureQuery("ReadAddressById");
 query.setParameter("P_ADDRESS_ID", 12345);
 List<Address> result = query.getResultList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM