java - 如何在 JPA 2.1 中映射来自 NameStoredProcedure 的非实体结果集?

标签 java postgresql jpa

我正在使用 jpa 2.1 调用一个 postgresql 过程,并想将结果集转换为一个名为 StoreAndCategoryID 的非实体类,其中包含两个整数字段:storeid、categoryid。这两个字段是从过程返回的字段。

@NamedStoredProcedureQuery(
    name = "Category.func_getcategorybytextsearchid",
    procedureName = "func_getcategorybytextsearchid",    
    parameters = {@StoredProcedureParameter(name = "textsearchid", type = Integer.class,
                                            mode = javax.persistence.ParameterMode.IN ),
          @StoredProcedureParameter(name = "mycursor", type = void.class, 
                                    mode = ParameterMode.REF_CURSOR )}
)

下面的代码是在Postgresql上执行的proc

CREATE OR REPLACE FUNCTION func_getcategorybytextsearchid(textsearchid integer )
  RETURNS refcursor  AS
$BODY$
declare mycursor refcursor ;
BEGIN
mycursor   = 'mycursor';

OPEN mycursor FOR (
            select storeid, categoryid 
            from item_full_text_search
            where itemfulltextsearchid = $1;

RETURN mycursor ;
end;

下面的java代码展示了我是如何调用程序的

StoredProcedureQuery q = 
em.createNamedStoredProcedureQuery("Category.func_getcategorybytextsearchid");
q.setParameter("textsearchid", textsearchid);

if (q.execute())
{
   //the result set needs to convert to StoreAndCategoryID class if possible.
   StoreAndCategoryID storeAndCategoryID  =  q.getOutputParameterValue("mycursor");  
}

public class StoreAndCategoryID
{
        int storeid;
        int categoryid;
}

如何更改@NamedStoredProcedureQuery 以返回/转换非实体类 StoreAndCategoryID?

谢谢,

最佳答案

您不能使用 StoredProcedureQuery 将存储过程结果集映射到非实体类。 但是,如果您要使用(如果您可以使用 JPQL 查询而不是存储过程调用)TypedQuey,您可以使用 JPQL constructor expression@SqlResultSetMappingNativeQuery

关于java - 如何在 JPA 2.1 中映射来自 NameStoredProcedure 的非实体结果集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25939624/

相关文章:

java - JPA AttributeConverter 使 hibernate 在事务中对整个表生成更新语句

java - Hibernate 1 个模型的多个表名

java - JPA(Hibernate)列映射中的原始类和包装类之间有什么区别?

ruby-on-rails - 如何在不同的环境中运行 rspec 测试?

java - 添加两个数字而不是合并

java - 查找 Java 函数的开头和结尾

java - xmlInputFactory.createXMLStreamReader 在 Weblogic 上给出 null

java - 如何为多用户 Java 应用程序设计/保留用户角色(当前和已注册)?

ruby-on-rails - Rails:PG::NotNullViolation:错误:列 "id"中的空值违反了非空约束

java - 如何在JPA/DB2中动态添加Where条件