我正在尝试调用我在Postgres DB中定义的函数。
CREATE OR REPLACE FUNCTION bacon()
RETURNS text AS
$BODY$
SELECT cast('ingeborg' as text)
$BODY$
LANGUAGE sql STABLE;
ALTER FUNCTION bacon()
OWNER TO my_user;
在我的Spring Repository中,我尝试调用函数
@Repository
public class ItemRepository {
@PersistenceContext(name = "com.project.persistenceUnit")
private EntityManager entityManager;
public Collection<ItemView> findBy() {
String statement = "SELECT * FROM schema.bacon()";
String result = (String) entityManager.createNativeQuery(statement)
.getSingleResult();
}
}
当我尝试从存储库中获取数据时,我收到以下错误
11.04.2014 11:34:00.177 [main] WARN o.h.e.jdbc.spi.SqlExceptionHelper:144 @ SQL Error: 0, SQLState: 42883
11.04.2014 11:34:00.177 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper:146 @ ERROR: Function schema.bacon() does not exist
SQLState 42883是'undefined_function'(http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html)
该功能在pgAdmin中调用时可以正常工作。
我做错了什么?如何调用已定义的函数?
更新
我连接到错误的数据库,必须遵循以下post:
public class MyExtendedPostgresSQLDialect extends PostgreSQL9Dialect {
public MyExtendedPostgresSQLDialect() {
super();
registerFunction("bacon", new PostgresBacon());
}
}
public class PostgresBacon implements SQLFunction {
@Override
public boolean hasArguments() {
return false;
}
@Override
public boolean hasParenthesesIfNoArguments() {
return false;
}
@Override
public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException {
return TextType.INSTANCE;
}
@Override
public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory) throws QueryException {
return "bacon()";
}
}
答案 0 :(得分:0)
我认为在创建函数和调用函数时,search_path不会设置为相等。 对于exp:
digoal=# show search_path;
search_path
----------------
"$user",public
(1 row)
digoal=# \c digoal digoal
You are now connected to database "digoal" as user "digoal".
digoal=> create function f_test1() returns void as $$
digoal$> declare
digoal$> begin
digoal$> end;
digoal$> $$ language plpgsql;
CREATE FUNCTION
digoal=> select f_test1();
f_test1
---------
(1 row)
digoal=> \c digoal postgres
You are now connected to database "digoal" as user "postgres".
digoal=# select f_test1();
ERROR: function f_test1() does not exist
LINE 1: select f_test1();
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
digoal=# \dn
List of schemas
Name | Owner
--------+----------
digoal | postgres
public | postgres
(2 rows)
digoal=# \df digoal.f_test1
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+---------+------------------+---------------------+--------
digoal | f_test1 | void | | normal
(1 row)
digoal=# \df public.f_test1
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
(0 rows)