【发布时间】:2022-01-10 12:50:38
【问题描述】:
我正在寻找一种 JpaRepository 方法来在使用用户名条件重置用户提供的密码时更新它。提前致谢
【问题讨论】:
-
您有用户实体吗?所以只需更改它并调用 save()
标签: spring-boot spring-mvc jpa spring-data-jpa jpa-2.1
我正在寻找一种 JpaRepository 方法来在使用用户名条件重置用户提供的密码时更新它。提前致谢
【问题讨论】:
标签: spring-boot spring-mvc jpa spring-data-jpa jpa-2.1
根据文档:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query,查看使用 JPA 创建自定义查询方法。
对于您的用例,以下将允许您更新正确的用户密码:
@Repository
public interface UserRepository extends JpaRepository<User, UUID> {
@Query("update User u set u.password= ?1 where u.username = ?2")
void updatePassword(String username, String password);
}
【讨论】:
在 Spring Data JPA 中,无论何时执行更新,都需要使用 @Modifying 和 @Query。未能使用@Modifying 将导致InvalidDataAccessApiUsage 异常。
找到下面的代码
@Repository
public interface UserRepository extends JpaRepository<User, UUID> {
@Modifying
@Query("update User u set u.password= :password where u.username = :username")
void updatePassword(@Param("username") String username, @Param("password") String password);
}
【讨论】: