JPQL:如果不存在则更新

时间:2013-08-20 19:36:07

标签: mysql hibernate sql-update jpql

我正试图在JPA / Hibernate / MySQL应用程序中实现类似的东西:

UPDATE UserRating ur SET ur.item = :newItem WHERE ur.item = :oldItem AND NOT EXISTS (SELECT ur2 FROM UserRating ur2 WHERE ur.user = ur2.user AND ur2.item = :newItem)

所以,我想只更新一些行,如果它们是唯一的(用户/项目组合必须是唯一的)。

我正在

Caused by: java.sql.SQLException: You can't specify target table 'user_rating' for update in FROM clause

使用当前的JPQL。

1 个答案:

答案 0 :(得分:0)

一种方法是将其变为JOIN

UPDATE UserRating r JOIN
(  
  SELECT user, item 
    FROM UserRating ur
   WHERE item = :oldItem 
     AND NOT EXISTS 
  (
    SELECT * 
     FROM UserRating 
    WHERE user = ur.user 
      AND item = :newItem
  )
) q ON r.user = q.user 
   AND r.item = q.item
   SET r.item = :newItem

这是 SQLFiddle 演示