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
谢谢
# 1 楼答案
不能使用}中的{a2}
StoredProcedureQuery
将存储过程结果集映射到非实体类。 但是,如果您使用(如果您可以使用JPQL查询而不是存储过程调用)TypedQuey
,那么您可以使用JPQL constructor expression 或者{# 2 楼答案
您可以使用@SQLResultsMapping和@ConstructorResult来实现