首页 > 解决方案 > 如何使用 JPA 或 JDBC 使用 REF_CURSOR 调用 PL/SQL 函数

问题描述

我在 PL/SQL 中创建了函数,它返回我的模式中所有表的名称。

CREATE OR REPLACE FUNCTION dbINFO
return sys_refcursor AS 
table_info sys_refcursor;
begin
    open table_info
        for select table_name from all_tables where owner = 'HOMEUSER';

        return table_info;
end;

我想使用 JDBC 或 JPA 来调用它。

我该怎么做?我几乎尝试了一切,但没有结果。

标签: javaspringoraclejpajdbc

解决方案


在您的任何实体类上创建命名本机查询。

@NamedNativeQuery(name="getAllTablesOwnedByHomeUser",
callable=true , query = "{? = call dbINFO()}",
resultClass = Pojo.class) //Pojo is class whch u r using 2 map resltset.


 //Field name in Pojo class and Table columns name should match which are returned 
   // by the cursor

现在使用您的 EntityManager 调用命名查询,如下所示。

  EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
TypedQuery<Pojo.class> q = em.createNativeQuery("getAllTablesOwnedByHomeUser",Pojo.class);
List<Pojo> tables = q.getResultList();
em.getTransaction().commit();
em.close();

推荐阅读