简体   繁体   中英

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?

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.

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();

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.

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