【问题标题】:JPQL and Entities (java.lang.IllegalArgumentException)JPQL 和实体 (java.lang.IllegalArgumentException)
【发布时间】:2017-09-20 04:51:22
【问题描述】:

我正在创建一个需要向各种用户显示通知表的 Web 应用程序。出于某种原因,我编写的 JPQL 查询抛出了 java.lang.IllegalArgumentException。我的应用程序已经有一个事务表,使用相同的方法 (afaik) 进行结构化和查询,效果很好。

我一直在改组代码,改变变量名和字符大小写数小时试图让它工作,但我仍然每次都遇到异常。有谁知道我哪里出错了?

我的 NotificationEntity 如下:

    @Table(name="notificationentity")
    @NamedQuery(name="fetch_user_notifications", query="SELECT n FROM NotificationEntity n WHERE n.notificationrecipient=:username")
    @Entity
    public class NotificationEntity implements Serializable
    {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;

      @NotNull
      String notificationSender;

      @NotNull
      String notificationrecipient;

      ... other fields + methods
    }

JPQL 查询是从使用以下方法实现接口 (NotificationStorageService) 的 EJB (NotificationStorageServiceBean) 调用的:

    @Override
    public synchronized List<NotificationEntity> getUserNotificationList(String username)
    {
      List notifications;
      notifications = em.createNamedQuery("fetch_user_notifications").setParameter("notificationrecipient", username).getResultList();
      return notifications;
    }

从我的 .xhtml UI 的 CDI 支持 bean 调用 EJB 方法,使用 FacesContext 的当前登录用户为这些方法提供参数。

    @EJB
    NotificationStorageService notificationStore;

    public List<NotificationEntity> getUserNotificationList()
    {
      return notificationStore.getUserNotificationList(this.currentUser);
    }

我得到的确切错误是: java.lang.IllegalArgumentException:您尝试使用查询字符串 SELECT n FROM NotificationEntity n WHERE n.notificationrecipient=:username 中不存在的 notificationrecipient 名称设置参数值。

【问题讨论】:

    标签: glassfish ejb jpql


    【解决方案1】:

    JPQL 查询中的参数名称以冒号开头。所以只需使用

    setParameter("username", username)
    

    【讨论】:

    • 非常感谢!这一直让我发疯。我显然误解了 setParameter 方法。我以为我应该引用实体字段,而不是我在命名查询中设置的参数。这在我的事务表中有效,因为实体字段、表列标题和参数都共享相同的名称
    猜你喜欢
    • 2020-04-24
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 2018-09-01
    • 2018-07-16
    • 2019-05-18
    相关资源
    最近更新 更多