【问题标题】:How to avoid joining table when querying by a foreign key?外键查询时如何避免加入表?
【发布时间】:2020-02-02 11:59:47
【问题描述】:

我有一个 Comment 类,其 user 属性定义为:

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    @NonNull
    private User user;

我有一个CommentRepository

public interface CommentRepository extends CrudRepository<Comment, Integer> {
    List<Comment> findByUserId(Integer userId);
}

我想通过他的 id 查询特定用户的 cmets。

我正在这样做:

commentRepository.findByUserId(userId);

一切正常,除了查询看起来像:

select
    comment0_."id" as id1_1_,
    comment0_."text" as url2_1_,
    comment0_."user_id" as user_id3_1_
    from
        "comments" comment0_
    left outer join
        "users" user1_
    on comment0_."user_id"=user1_."id"
    where
    user1_."id"=?

我想避免这种连接,因为我可以通过comments 表中的user_id 列直接查询。

我不想使用@Query注解,我认为应该有更聪明的方法。

【问题讨论】:

    标签: java spring spring-boot jpa


    【解决方案1】:

    @ManyToOne(optional = true) 和 @JoinColumn(nullable = true) 的默认值会导致此额外连接。你可以试试,

    @ManyToOne(fetch=FetchType.LAZY, optional = false)
    @JoinColumn(name="`user_id `", nullable = false)
    

    【讨论】:

      猜你喜欢
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-12
      • 2023-03-11
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      相关资源
      最近更新 更多