有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何映射来自JPA2.1中名称存储过程的非实体结果集?

我正在使用JPA2.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上执行的过程

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;
}

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

谢谢


共 (2) 个答案

  1. # 1 楼答案

    不能使用StoredProcedureQuery将存储过程结果集映射到非实体类。 但是,如果您使用(如果您可以使用JPQL查询而不是存储过程调用)TypedQuey,那么您可以使用JPQL constructor expression 或者{}中的{a2}

  2. # 2 楼答案

    您可以使用@SQLResultsMapping和@ConstructorResult来实现

    @SqlResultSetMapping(name = "CalendarsMapping", classes = {
        @ConstructorResult(targetClass = Calendar.class, columns = { @ColumnResult(name = "OutDate"),
                @ColumnResult(name = "CategoryID", type = Long.class), @ColumnResult(name = "CategoryName"),
                @ColumnResult(name = "DepositDate"), @ColumnResult(name = "EventDate"),
                @ColumnResult(name = "EventType"), @ColumnResult(name = "Status"),
                @ColumnResult(name = "Effective", type = String.class),
                @ColumnResult(name = "Indicator", type = String.class), @ColumnResult(name = "TermDate"),
                @ColumnResult(name = "TID"), @ColumnResult(name = "TName"), @ColumnResult(name = "Series"),
                @ColumnResult(name = "Symbol"), @ColumnResult(name = "TType", type = String.class) }) })
    
    
    
    StoredProcedureQuery procedureQuery = entityManager.createStoredProcedureQuery(
                "GetDepAndTerm", "CalendarsMapping");
    procedureQuery.getResultList();