2010-05-12 39 views
1

我有一個SQL Server存儲過程是這樣的:休眠,存儲過程和無效參數指數誤差

CREATE PROCEDURE [dbo].[my_stored_procedure] 
    (
     @num INT, 
     @name VARCHAR(50), 
     @start_date DATETIME, 
     @end_date DATETIME 
    ) 
AS 
BEGIN 
... 
END 

並配有NamedNativeQuery,看起來像這樣一個實體對象:

@Entity 
@NamedNativeQuery(
    name = "myObject.myStoredProcedure", 
    query = "call my_stored_procedure(:num, :name, :start_date, :end_date)", 
    callable = true, 
    readOnly=true, 
    resultSetMapping="implicit" 
) 
@SqlResultSetMapping(
    name="implicit", 
    [email protected](entityClass=org.mycompany.object.MyObject.class) 
) 
public class MyObject implements Serializable { 
... 

但是當我嘗試在我的DAO中調用它時,像這樣:

List<MyObject> objects = (List<MyObject>) getHibernateTemplate().execute(new HibernateCallback() { 
      @Override 
      public Object doInHibernate(Session session) throws HibernateException { 
       return session.getNamedQuery("myObject.myStoredProcedure") 
       .setInteger("num", num) 
       .setString("name", name) 
       .setDate("start_date", startDate) 
       .setDate("end_date", endDate) 
       .list(); 
      } 
     }); 

但是,我收到此錯誤:

12 May 2010 10:55:43,040 100833 [http-8080-Processor23] ERROR org.hibernate.util.JDBCExceptionReporter - Invalid parameter index 4. 
12 May 2010 10:55:43,042 100835 [http-8080-Processor23] FATAL org.mycompany.web.controller.BasePagingController - org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query 
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query 

它似乎期待另一個參數,如返回參數,但我嘗試添加'?'到這個調用,所有的Hibernate文檔都提出了這個問題。

任何幫助,將不勝感激。由於

回答

3

Hibernate Documentation on calling stored procedures狀態:

The recommended call form is standard SQL92: { ? = call functionName(<parameters>) } or { ? = call procedureName(<parameters>) }. Native call syntax is not supported.

所以在你的第二個片段中的4號線可能應該

query = "{ ? = call my_stored_procedure(:num, :name, :start_date, :end_date) }",

我不知道,你的程序返回,但你可能還想檢查以下內容。
更多Hibernate文檔:

For Sybase or MS SQL server the following rules apply:

  • The procedure must return a result set. Note that since these servers can return multiple result sets and update counts, Hibernate will iterate the results and take the first result that is a result set as its return value. Everything else will be discarded.
  • If you can enable SET NOCOUNT ON in your procedure it will probably be more efficient, but this is not a requirement.