【问题标题】:Is there a JpaRepository method which can save a provided password where username condition?是否有 JpaRepository 方法可以在用户名条件下保存提供的密码?
【发布时间】:2022-01-10 12:50:38
【问题描述】:

我正在寻找一种 JpaRepository 方法来在使用用户名条件重置用户提供的密码时更新它。提前致谢

【问题讨论】:

  • 您有用户实体吗?所以只需更改它并调用 save()

标签: spring-boot spring-mvc jpa spring-data-jpa jpa-2.1


【解决方案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);

}

【讨论】:

    【解决方案2】:

    在 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);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-20
      • 1970-01-01
      • 2018-11-03
      • 2011-12-27
      • 2014-08-07
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      相关资源
      最近更新 更多