【问题标题】:JAVA Spring Boot - existsByColumne1AndNotColumn2 Repository queryJAVA Spring Boot - existsByColumne1AndNotColumn2 Repository 查询
【发布时间】:2020-04-24 15:35:48
【问题描述】:

我正在使用 Java Spring Boot,我想在其中创建默认查询以查找用户是否已经存在给定手机号码而不是给定用户 ID。原始查询是这样的

SELECT * FROM `user` WHERE mobile = "9898989898" AND user_id != 123

我确实发现要检查单个列中是否存在该列中的数据,我们可以在 Repository 类中执行类似的操作

Boolean ExistWithMobile(String mobile)

如果找到具有给定手机号码的行,这将返回真或假。

我希望查询类似于上面的方式,但这不起作用

Boolean existsByMobileAndNotUserId(String mobile, Long userId);

无论此电话号码是否可用于其他用户 ID,这应该返回 true 或 false

我知道如何处理原始查询,正如我在问题开始时已经提到的那样,但我想要这种直接的查询方式,而不需要原始查询。

任何帮助将不胜感激。

【问题讨论】:

  • existsByMobileAndUserIdIsNot(String mobile, Long userId) 怎么样?
  • @bean 这就是我想要的。。谢谢你的回答!真的很感激!

标签: java sql spring-boot spring-data-jpa


【解决方案1】:

如果你不想使用原生 sql 查询,你可以改用 HQL。

在你的情况下:

@Query("from User u Where u.mobile = :mob and u.id != :id")
Optional<User> findUserByMobile(@Param("mob") String mobile, @Param("id") long id)

当你打电话时:

Optional<User> user = repo.findUserByMobile(mobile, uid);
if( user.isPresent() ) { ... }

这里是春季数据中@Query 的文档: Spring Data JPA

祝你好运

【讨论】:

    猜你喜欢
    • 2018-11-30
    • 1970-01-01
    • 2019-12-23
    • 2018-05-05
    • 1970-01-01
    • 2021-02-10
    • 2019-05-03
    • 2016-10-03
    • 2021-11-01
    相关资源
    最近更新 更多