如何使用Hibernate调用Oracle存储过程?

时间:2014-02-21 12:17:55

标签: java spring oracle hibernate

以下是我的Oracle存储过程

create or replace 
PROCEDURE "REPORT_HIBERNATE"(
start_year IN NUMBER,
output_data OUT SYS_REFCURSOR
)
AS 
BEGIN
DECLARE 
select_query LONG;

BEGIN
select_query :='SELECT 
  GLOBAL_ID,
  PROJECT_NUMBER,
  FISCAL_YEAR,
  FISCAL_MONTH,
  WEEK_END_DATE,
  ACTIVITY,
  COST_CENTER,
  ACTUAL_HOURS,
  APPROVED_HOURS,
  NORMALIZED_HOURS
FROM TS_TBTIMECARD_WEEKLY_DATA
where FISCAL_YEAR in
(SELECT  FISCAL_YEAR        
FROM TS_TBTIMECARD_WEEKLY_DATA        
where      FISCAL_YEAR               = ' ||start_year|| '
 )';
OPEN output_data FOR select_query;
END;
END REPORT_HIBERNATE;

以下是实体类:

@Entity
@SequenceGenerator(name="wkseq", initialValue=1, allocationSize=1)
@Table(name = "TS_TBTIMECARD_WEEKLY_DATA")



@NamedNativeQuery(name = "call_REPORT_HIBERNATE_procedure",
query = "{ CALL REPORT_HIBERNATE(:start_year) }", 
resultClass = TimecardWeeklyData.class, hints = {
@javax.persistence.QueryHint(name = "org.hibernate.callable", value = "true") })



public class TimecardWeeklyData {
...
}

DAOImpl:

Query query = sessionFactory.getCurrentSession().getNamedQuery("call_REPORT_HIBERNATE_procedure");

        query.setParameter("start_year",2014); 
    List result = query.list();

我收到以下异常: Hibernate:{CALL REPORT_HIBERNATE(?)} org.hibernate.exception.GenericJDBCException:无法执行查询 ... 和 引起:java.sql.SQLException:列索引无效

Plz让我知道如何在Spring中使用Hibernate Annotation调用这个存储过程?

2 个答案:

答案 0 :(得分:1)

您的OUT参数不是第一个。如果您可以修改过程,请重新排列参数以使OUT参数成为第一个参数,然后在@NamedNativeQuery注释中对其进行说明。

query = "{ CALL REPORT_HIBERNATE(?, :start_year) }",

答案 1 :(得分:1)

考虑到你有一个dir='.' # sample target dir for file in "$dir"/*.txt; do contents=$(<"$file") # read contents of file $file # ... work with "$contents" done OUT参数:

SYS_REFCURSOR

您可以像这样调用存储过程:

CREATE OR REPLACE PROCEDURE post_comments ( 
   postId IN NUMBER, 
   postComments OUT SYS_REFCURSOR ) 
AS 
BEGIN
    OPEN postComments FOR
    SELECT *
    FROM post_comment 
    WHERE post_id = postId; 
END;

有关更多详细信息,请查看this article,其中说明了如何使用简单类型和数据库函数调用存储过程。