Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with positional parameters in JPA native query

I'm trying to do:

String sql = "SELECT email FROM users WHERE (type like 'B') AND (username like '?1')";
List results = em.createNativeQuery(sql).setParameter(1, username).getResultList();

But I get IllegalArgumentException that tells me that the parameter is out of bounds. What am I doing wrong?

like image 727
Eldad Mor Avatar asked Nov 10 '10 12:11

Eldad Mor


2 Answers

There shoudn't be quotes around the parameters. Try this instead:

String sql = "SELECT email FROM users WHERE (type like 'B') AND (username like ?1)";

You might also want to double-check that you really mean type like 'B' as this probably doesn't do what you think it does.

like image 167
Mark Byers Avatar answered Oct 29 '22 22:10

Mark Byers


a) Why would you use native SQL for a simple query like this? Use JPQL.
b) Why use like if you don't use wildcards? Use = instead.

String jpql =
  "SELECT u.email FROM users u WHERE (u.type = 'B') AND (u.username = '?1')";

List results = 
    em.createQuery(jpql)
      .setParameter(1, username)
      .getResultList();
like image 24
Sean Patrick Floyd Avatar answered Oct 29 '22 21:10

Sean Patrick Floyd