JPA 调用带参数的存储过程
JPA calling stored procedure with argument
我的 postgreSQL 数据库中有这个过程:
CREATE OR REPLACE FUNCTION getItemsForCategory(categoryId integer)
RETURNS SETOF ITEM AS $_$
DECLARE
result ITEM;
BEGIN
FOR result IN SELECT *
FROM item it
JOIN item_category itcat ON it.id = itcat.item_id WHERE itcat.category_id = categoryId LOOP
RETURN NEXT result;
END LOOP;
END; $_$ LANGUAGE 'plpgsql';
使用终端效果很好,但我无法使用 JPA 调用它。这是我的代码片段(4 是参数 cateforyId 的值):
transactions.begin();
final StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("getItemsForCategory");
storedProcedureQuery.setParameter(1,4).execute();
final List<ItemEntity> itemEntityList = (List<ItemEntity>) storedProcedureQuery.getResultList();
transactions.commit();
在上面的 运行 代码之后我收到这个错误:
Exception in thread "main" java.lang.IllegalArgumentException:
You have attempted to set a parameter at position 1 which does not exist in this query string getItemsForCategory
有没有人知道如何正确设置参数的值?我还尝试使用 0 而不是 1 来设置参数,使用其他数据类型的参数(字符串、对象)调用 setParameter,但每次我都会收到熟悉的错误,如此处所示。非常感谢
您需要在设置值之前注册您的参数。
spq.registerStoredProcedureParameter("categoryId", int.class, ParameterMode.IN);
我的 postgreSQL 数据库中有这个过程:
CREATE OR REPLACE FUNCTION getItemsForCategory(categoryId integer)
RETURNS SETOF ITEM AS $_$
DECLARE
result ITEM;
BEGIN
FOR result IN SELECT *
FROM item it
JOIN item_category itcat ON it.id = itcat.item_id WHERE itcat.category_id = categoryId LOOP
RETURN NEXT result;
END LOOP;
END; $_$ LANGUAGE 'plpgsql';
使用终端效果很好,但我无法使用 JPA 调用它。这是我的代码片段(4 是参数 cateforyId 的值):
transactions.begin();
final StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("getItemsForCategory");
storedProcedureQuery.setParameter(1,4).execute();
final List<ItemEntity> itemEntityList = (List<ItemEntity>) storedProcedureQuery.getResultList();
transactions.commit();
在上面的 运行 代码之后我收到这个错误:
Exception in thread "main" java.lang.IllegalArgumentException:
You have attempted to set a parameter at position 1 which does not exist in this query string getItemsForCategory
有没有人知道如何正确设置参数的值?我还尝试使用 0 而不是 1 来设置参数,使用其他数据类型的参数(字符串、对象)调用 setParameter,但每次我都会收到熟悉的错误,如此处所示。非常感谢
您需要在设置值之前注册您的参数。
spq.registerStoredProcedureParameter("categoryId", int.class, ParameterMode.IN);