我正在使用 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。
我该如何解决?有什么建议么?