【问题标题】:join in spring data query repository加入spring数据查询存储库
【发布时间】:2021-11-11 09:43:10
【问题描述】:
@Query("select u from User u join u.favoriteRestos s where u.id = ?1 ")
User findByIdWithFavoriteRestos (Long userId);

O 在我的仓库中有这个查询,但不是返回一个带有空的 favoriteRestos 集合的用户而是返回一个空用户

也返回一个空用户:

@Query("select u from User u join fetch u.favoriteRestos s where u.id = ?1 ")
User findByIdWithFavoriteRestos (Long userId);

我也试过了:

@Query("select u from User u left join u.favoriteRestos s where u.id = ?1 ")
User findByIdWithFavoriteRestos (Long userId);

【问题讨论】:

  • 您可能需要左连接,否则如果没有最喜欢的restos,则连接不会产生任何结果。
  • 最可能的解释是您输入的id 值与底层数据库表中的任何记录都不匹配。检查您的数据。
  • @Thomas 对于 SQL 是正确的,对于 Hibernate 不是正确的。在 HQL 中,即使 favoriteRestos 集合为空,关联的用户实体仍应返回 AFAIK。
  • 如果要初始化集合,应该是join fetch 而不是join?见thorben-janssen.com/…
  • @TimBiegeleisen 确切地说...... OP 的查询和描述看起来像实际目标是获取集合,即获取 ID 为 x 的用户并急切地加载那里的任何 favoriteRestos。因此,不只是JOIN 会影响结果集,而应该是JOIN FETCH,它不会影响结果集。

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


【解决方案1】:

它没有找到任何用户,因为join 是一个内连接。需要添加left关键字:

@Query("select u from User u left join fetch u.favoriteRestos s where u.id = ?1 ")
User findByIdWithFavoriteRestos (Long userId);

P.S.:fetch 如果要填充集合,如果您有默认(惰性)多对多映射,则也需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 2021-04-16
    • 1970-01-01
    • 2018-07-12
    • 2013-12-01
    相关资源
    最近更新 更多