1

I am using JPA through Java EE and have the following native postgresql query:

@NamedNativeQuery(name = "Player.getStandardDev", query ="SELECT STDDEV(?1) FROM Player WHERE ?2 IS NOT NULL")

(I realise the check for IS NOT NULL is probably not needed, but this is not the source of the problem in this case).

I then have the following code trying to execute the query:

Query query = getEntityManager().createNamedQuery("Player.getStandardDev");
query.setParameter(1, attribute);
query.setParameter(2, attribute);
return (BigDecimal) query.getSingleResult();

When getSingleResult() is called, I receive the following error:

org.postgresql.util.PSQLException: ERROR: function stddev(character varying) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 8

I assume this is because the calls to setParameter are not working correctly and so are not replacing the ?s

Is there any other way to use native queries where you can set parameters.

1 Answer 1

1

The error occurs because when you set a parameter to the query it is evaluated as a string literal in the generated SQL not as a column name. So it becomes

SELECT STDDEV('column_name') FROM Player ...

instead of

SELECT STDDEV(column_name) FROM Player ...

which causes the error because the function expects column name or numeric value.

You can't dynamically set column name in JPA query. You must either hardcode it somehow or use other ways of constructing the query. See this SO post for more details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.