0

我正在使用 Spring Data 并创建了以下查询:

public interface UserRepository extends JpaRepository<User, Long>, QueryDslPredicateExecutor<User> {

    @Modifying
    @Query("DELETE FROM User u WHERE u.userDetails.userName = :username")
    public void deleteByUserName(@Param("username") String userName);
}

在运行时我不断得到:

ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'cross join UserDetails userdetail1_ where User_Name='rb2x5yv7'' at line 1

我将 MySql 与 MySQL5Dialect 一起使用。

我的查询有什么问题?

**

更新:

**

这个线程之后,我更改了我的代码:

public interface UserRepository extends JpaRepository<User, Long>, QueryDslPredicateExecutor<User> {

    @Modifying
    @Query("DELETE FROM User u WHERE u.id in (SELECT u1.id FROM User WHERE u1.userDetails.userName = :username)")
    public void deleteByUserName(@Param("username") String userName);
}

但现在我得到:

org.hibernate.QueryException: Unable to resolve path [u1.id], unexpected token [u1] [DELETE FROM com.bs.dal.domain.User u WHERE u.id in (SELECT u1.id FROM com.bs.dal.domain.User WHERE u1.userDetails.userName = :username)]

**

更新 2:

**

看来我在子查询中缺少“u1”。将查询更改为:

 @Query("DELETE FROM User u WHERE u.id in (SELECT u1.id FROM User u1 WHERE u1.userDetails.userName = :username)")

现在我得到:

org.hibernate.exception.GenericJDBCException: You can't specify target table 'Users' for update in FROM clause.

我知道会发生这种情况,因为您无法修改在 SELECT 部分中使用的同一个表。此行为记录在:dev.mysql.com/doc/refman/5.6/en/update.html。

我该如何解决?有什么建议么?

4

2 回答 2

1

为了让它发挥作用,我必须做两件事:

第一个,使用这个查询:

public interface UserRepository extends JpaRepository<User, Long>, QueryDslPredicateExecutor<User> {

    @Modifying
    @Query(name = "Delete User by UserName", value = "DELETE FROM User u WHERE u.id IN (SELECT ud.id FROM UserDetails ud WHERE ud.userName = :username)")
    public void deleteByUserName(@Param("username") String userName);
}

第二:

我必须确保删除级联在数据库中得到很好的实现。由于某种原因,它不是自动生成的。你可以看到我与这一点相关的新线程。

于 2012-12-22T18:35:45.877 回答
0

在DELETE 语句中分配表别名的正确方法是:

DELETE u FROM User u WHERE u.userName = :username
       ^

当然,如果只涉及一张表,您可以简单地省略别名:

DELETE FROM User WHERE userName = :username
于 2012-12-21T09:30:42.153 回答