简体   繁体   English

JPA使用参数调用存储过程

[英]JPA calling stored procedure with argument

I have this procedure in my postgreSQL database: 我的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';

which works excellent using terminal, but I have trouble with calling it using JPA. 使用终端可以很好地工作,但是使用JPA调用它有麻烦。 Here is my code snippet(4 is value of argument cateforyId): 这是我的代码片段(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();

after running code above I receive this error: 在运行上面的代码后,我收到此错误:

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

Has anyone some idea how to set the value of argument correctly? 有谁知道如何正确设置参数值? I've also tried to set parameter using 0 instead of 1, calling setParameter with others datatypes of arguments (String,Object) but everytime I am receiving familiar kind of error like the one, which is shown there. 我也尝试使用0而不是1来设置参数,并使用其他数据类型的参数(String,Object)调用setParameter,但是每次我收到类似的错误,如此处所示。 Thank you very much 非常感谢你

You need to register your parameters, before setting values. 您需要先注册参数,然后再设置值。

spq.registerStoredProcedureParameter("categoryId", int.class, ParameterMode.IN);

See this link . 看到这个链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM