java.lang.IllegalArgumentException:修改查询只能使用void或int/Integer作为返回类型!同时尝试在JpaRepository中使用@Query

snd*_*ndu 0 java mysql spring hibernate spring-data-jpa

我需要更新mysql表中的字符串值.为此,我写了一个方法如下.

@Repository
public interface NotificationRepository extends JpaRepository<Notification, Long> {

    @Modifying
    @Query("update Notification msg set msg.message = ?1 where msg.applicationUser.id = ?2")
    String createNewNotification(String message, Long id);

}
Run Code Online (Sandbox Code Playgroud)

我得到以下例外.

java.lang.IllegalArgumentException: Modifying queries can only use void or int/Integer as return type!
Run Code Online (Sandbox Code Playgroud)

我无法更新表格中的字符串值.只有void或int是可能的吗?这是什么意思?我该如何处理此异常?请帮忙.

Mat*_* G. 6

您可以更新数据库中的字符串值(您已经通过消息参数值执行此操作)。使用 @Modifying 批注时,不能将 String 对象作为数据库查询的返回值返回。我建议您将返回类型更改为 void 或 int 以指示失败成功:

@Modifying
@Query("update Notification msg set msg.message = ?1 where msg.applicationUser.id = ?2")
void createNewNotification(String message, Long id);
Run Code Online (Sandbox Code Playgroud)

或者

@Modifying
@Query("update Notification msg set msg.message = ?1 where msg.applicationUser.id = ?2")
int createNewNotification(String message, Long id);
Run Code Online (Sandbox Code Playgroud)

int/Integer 返回值是在数据库中更新的行数。因此,如果该值 > 0,则您会收到查询执行成功的反馈。

还尝试查看@Modifying 的选项。


Zer*_*mus 5

正如错误所示,Modifying queries can only use void or int/Integer as return type您只能返回void或整数/ int,表示查询已更新了多少行.

改变这一点,应该没有问题.

  @Modifying
    @Query("update Notification msg set msg.message = ?1 where msg.applicationUser.id = ?2")
    void createNewNotification(String message, Long id);
Run Code Online (Sandbox Code Playgroud)