2013-11-21 38 views
4

我想使用JPA調用Oracle函數。我在這個主題上找到了this thread如何調用使用Hibernate/JPA返回字符串的Oracle函數?

但是我的Oracle函數只返回一個字符串。不是某種實體的結果。我想是這樣的:

@NamedNativeQuery(name = "myFuncCall", 
     resultSetMapping = "myResultSetMapping", 
     query = "{ ? = call schema.mypkg.somefunc(:id) }", 
     hints = { @javax.persistence.QueryHint(name = "org.hibernate.callable", value = "true") } 
) 

@SqlResultSetMapping(name = "myResultSetMapping", 
    columns = { @ColumnResult(name="somename") } 
) 

當我打電話這樣

Query query = em.createNamedQuery("myFuncCall", String.class).setParameter("id", "42"); 
     String res = (String) query.getSingleResult(); 

查詢我得到

Hibernate: { ? = call schema.somefunc(?) } 
18:21:11.222 [main] WARN o.h.util.JDBCExceptionReporter - SQL Error: 6550, SQLState: 65000 
18:21:11.222 [main] ERROR o.h.util.JDBCExceptionReporter - ORA-06550: Row 1, Column 13: 
PLS-00382: This expression has the wrong type 
ORA-06550: Row 1, Column 7: 
PL/SQL: Statement ignored 

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query 
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1389) 
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1317) 
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:307) 

任何想法?

+0

你有沒有發現任何有用的東西,我也一起砍了其他東西 – NimChimpsky

+0

不,它仍然像下面一樣,不幸的是。 – Stefan

回答

2

我們結束了使用CallableStatement。它的工作原理,但告訴我,如果有更好的解決方案!

String funcCall = "{? = call schema.mypkg.somefunc(?)}"; 
Connection conn = ((SessionImpl)em.getDelegate()).connection(); 
CallableStatement stmt = conn.prepareCall(funcCall); 
stmt.setInt(2, 42); 
stmt.registerOutParameter(1, Types.CHAR); 
stmt.executeUpdate(); 
String result = stmt.getString(1); 
0

我這樣做一個相當古怪的方式,你必須返回一個refcursor。因此,請確保您的函數返回一個引用遊標和不喜歡下面的東西:

result_string := doSoemthing 
    open l_refcursor for select result_string as str from dual; 
    return l_refcursor; 

然後創建一個「虛擬」實體

@Entity 
public class NativeString { 
    private String str; 

    @Id 
    @Column(name = "str") 
    public String getStr() { 
     return str; 
    } 

    public void setStr(String str) { 
     this.str = str; 
    } 
} 

,您可以使用本機查詢功能

@NamedNativeQueries({ 
     @javax.persistence.NamedNativeQuery(name = "whatevs", query = "" + 
       "{? = call myfunction(:id)}", resultClass = NativeString.class, 
       hints = { 
         @javax.persistence.QueryHint(name = "org.hibernate.callable", value = "true") 
       } 

     ) 

}) 

這就像它變得醜陋一樣...有沒有很好的方式與hierbnate和存儲過程和函數afaik。

相關問題