I have a postgres query with params, in my Java code, am using stringBuilder to build the query and then createNativeQuery to create query and populating the params. However if I run the query in my gui, it gives me the result which is expected, but gives error when executing via code. I'm a newbie on postgres and have seen some questions with the nearly same problems that I need to cast the params in the query, but I do have IN param inside my query which is list, I've tried some solutions but didn't worked.
I' am getting error as :-> "error": "Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1" Position: 249
StringBuilder sb = new StringBuilder();
sb.append(" SELECT comments.comment, mapping.user_id,
mapping.comment_id, mapping.comment_state,
mapping.created_at FROM comments ").append(" comment
JOIN ").
append(" user_comment_mapping mapping ON
mapping.comment_id = comment.id WHERE
mapping.user_id IN ? AND mapping.comment_state = ?
");
final Query query = em.createNativeQuery(sb.toString());
query.setParameter("1", userIds);
query.setParameter("2",
2);
List<Object[]> list = query.getResultList();
Thanks!
It seems you are mixing between parameter holder and name so.
If you want to use holder :
mapping.user_id IN ? AND mapping.comment_state = ?
then
query.setParameter(1, userIds);
query.setParameter(2, 2);
If you want to use names :
mapping.user_id IN :ids AND mapping.comment_state = :stat
query.setParameter("ids", userIds);
query.setParameter("stat", 2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.