【问题标题】:IllegalArgumentException: Could not locate named parameterIllegalArgumentException:找不到命名参数
【发布时间】:2020-06-04 19:54:27
【问题描述】:

我将 Map 作为以下方法的参数传递:

    public List<User> getByParameterOrAll(Map<String, String> paramsMap) {
    String email = null;
    String emailValue = null;
    String phone = null;
    String phoneValue = null;

    Iterator<Map.Entry<String, String>> entries = paramsMap.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        if (entry.getKey().equals("email")){
            email = entry.getKey();
            emailValue = entry.getValue();
        } else if (entry.getKey().equals("phone")){
            phone = entry.getKey();
            phoneValue = entry.getValue();
        }
    }

    List<User> users = em.createQuery("SELECT u FROM User u WHERE u.email=:emailValue AND u.phone=:phoneValue", User.class).
            setParameter(emailValue, email).
            setParameter(phoneValue, phone).
            getResultList();
    return users;
}

我抓住了“setParameter(emailValue, email)”这一行

java.lang.IllegalArgumentException: Could not locate named parameter [gmail@gmail.com], expecting one of [phoneValue, emailValue]

我附上我的测试屏幕

【问题讨论】:

  • paramsMap的值是什么
  • 您将变量传递给setParameter,而不是参数名称。您需要将setParameter(emailValue, email) 更改为setParameter("emailValue", emailValue)。 phoneValue 也是如此
  • 顺便说一句,如果您已经知道电子邮件和电话的预期键,请不要遍历映射条目,而是更愿意通过键查询映射 => emailValue = paramsMap.get("email")
  • YCF_L。不要清楚你的问题
  • 内瓦特。谢谢 - 我现在明白 mu 的错误了

标签: java hibernate hql entitymanager named-parameters


【解决方案1】:

您应该通过以下方式更正您的查询(请参阅documentation):

List<User> users = em.createQuery("SELECT u FROM User u WHERE u.email=:emailValue AND u.phone=:phoneValue", User.class).
            setParameter("emailValue", email).
            setParameter("phoneValue", phone).
            getResultList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-29
    • 2012-09-08
    • 2012-11-03
    • 2017-11-21
    • 2011-09-11
    • 2016-10-21
    • 2013-09-11
    • 2017-12-30
    相关资源
    最近更新 更多