【问题标题】:JPQL where in array queryJPQL where 数组查询
【发布时间】:2012-01-17 23:21:17
【问题描述】:

我正在尝试更新我的数组列表中具有 id 的每条记录,但我收到了这个错误:

IllegalStateException occured : org.hibernate.hql.QueryExecutionRequestException: Not supported for DML operations [update models.UserOnline uo SET currentRoom_id = :roomid where uo.id IN (:list)]

这就是我正在尝试的:

    Query update_query = JPA.em().createQuery("update UserOnline uo SET currentRoom_id = :roomid where uo.id IN (:list)");
    update_query.setParameter("roomid", null);
    update_query.setParameter("list", idlist);

    List<UserOnline> actual = update_query.getResultList();

有什么想法吗?

【问题讨论】:

    标签: java hibernate playframework jpql


    【解决方案1】:

    我会尝试update_query.executeUpdate();

    来自docs。

    【讨论】:

      【解决方案2】:

      就像 Gonzalo 已经说过的,您必须使用 executeUpdate()。

      这是因为您实际上是在修改数据。

      如果您想从数据库中获取数据,只能使用 getResultList() 或 getSingleResult()。

      一个小帮手: 如果您的查询具有以下形式,请使用 executeUpdate()

      UPDATE ... SET .. WHERE ..
      or
      DELETE ... WHERE ...
      

      如果查询看起来像,则使用 getResultList() 或 getSingleResult()

      SELECT ... FROM xxx WHERE ... 
      or just
      FROM xxx WHERE ... 
      

      【讨论】:

        【解决方案3】:

        好吧,如果我们使用 Spring Repositories(CrudRepository 或其任何类型),并且如果我们有一个带有更新查询的方法声明 也就是说,

        @Query("更新员工 e 设置 e.name= :name where e.id = :id") int updateEmployee(@Param("name") String name, @Param("id") Long id);

        然后我们会得到相关的Spring Exception org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations

        只要在方法上加上@Modifying注解就可以了。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-24
          • 2015-10-13
          • 1970-01-01
          • 2018-06-18
          • 1970-01-01
          • 2013-09-13
          • 2019-07-01
          • 1970-01-01
          相关资源
          最近更新 更多