拥有这些实体:
用户.java:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
private String username;
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
private List<Nickname> nicknames;
}
昵称.java:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "nickname")
public class Nickname {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String value;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@Override
public String toString() {
return "Nickname{" +
"id=" + id +
", value='" + value + '\'' +
'}';
}
}
和昵称存储库:
public interface NicknameRepository extends JpaRepository<Nickname, Long> {
@Transactional
@Modifying
// @Query("DELETE FROM Nickname n WHERE n.value = :value AND n.user.username = :username")
@Query("DELETE FROM Nickname n JOIN n.user u where n.value = :value AND u.username = :username")
void deleteNicknameByValue(@Param("username") String username, @Param("value") String value);
}
我正在尝试加入这两个实体,因为我需要来自
username
的 User
和来自 value
的 Nickname
。我明白了
java.lang.IllegalArgumentException: org.hibernate.query.SyntaxException: At 1:23 and token 'JOIN', mismatched input 'JOIN', expecting one of the following tokens: <EOF>, WHERE [DELETE FROM Nickname n JOIN n.user u where n.value = :value AND u.username = :username]
这个连接有什么问题吗?
来自文档
此处可以使用相对于 SELECT 查询的结构,DELETE 查询的结构非常简单。 DELETE 查询不能包含多个变量和 JOIN,也不能包含 GROUP BY、HAVING 和 ORDER BY 子句。
IN
子句来删除 Nickname
。
@Query("DELETE FROM Nickname n where n.value = :value AND n.id IN (SELECT n2.id FROM Nickname n2 JOIN n2.user u WHERE u.username = :username)")
void deleteNicknameByValue(@Param("username") String username, @Param("value") String value);