简体   繁体   中英

How to get OUTPUT value from stored procedure in hibernate (SQL SERVER)

I have stored procedure in MS SQL Server

CREATE PROC dbo.insertData 
    @param1 nvarchar(11),
    @param2 nvarchar(30),
    @ID bigint OUTPUT
AS 
BEGIN   
    INSERT INTO dbo.Adaptor (Col1, Col2) VALUES (@param1, @param2)
    SET @ID = SCOPE_IDENTITY(); 
END

And I want to get this generated ID as output parameter in java.

I have created a mapping file

<sql-query name="insertData" callable="true">
    <return alias="adaptor" class="MyClass">
        <return-property name="id" column="ID" />
    </return>
    { ? = call InsertData(:param1, :param2) }
</sql-query>

and trying to execute it from java

  Query query = entityManager.createNamedQuery("insertData");

            query.setParameter("param1", object);
            query.setParameter("param2", getName());
            // TODO try to use getSingleResult in tests
            List result = query.getResultList();

But I have exception java.sql.SQLException: Parameter #3 has not been set

If I remove ? = I got

java.sql.SQLException: Procedure or function 'insertData' expects parameter '@ID', which was not supplied.

Has anyone any idea how code/mapping file should look like? Thanks in advance

Query query = session.createSQLQuery(
    "CALL GetStocks(:stockCode)")
    .addEntity(Stock.class)
    .setParameter("stockCode", "7277");

List result = query.list();
for(int i=0; i<result.size(); i++){
    Stock stock = (Stock)result.get(i);
    System.out.println(stock.getStockCode());
}

from here

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