java JPA本机查询中的位置参数问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4144660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:00:16  来源:igfitidea点击:

Problem with positional parameters in JPA native query

javasqlhibernatejpa

提问by Eldad Mor

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?

但是我得到 IllegalArgumentException ,它告诉我参数超出范围。我究竟做错了什么?

回答by Mark Byers

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.

您可能还想仔细检查您的意思,type like 'B'因为这可能与您认为的不一样。

回答by Sean Patrick Floyd

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.

a) 为什么要使用本机 SQL 进行这样的简单查询?使用 JPQL。
b) 如果不使用通配符,为什么要使用 like?使用=来代替。

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