How to avoid joining table when querying by a foreign key?

Anton Ivanov :

I have a Comment class with a user property defined as:

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

I have a CommentRepository:

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

I want to query a particular user's comments by his id.

I'm doing this:

commentRepository.findByUserId(userId);

everything works fine except the query looks like:

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"=?

I want to avoid this join as I can query directly by the user_id column in a comments table.

I don't want to use a @Query annotation, I think there should be a smarter way.

Code_Mode :

The default value for @ManyToOne(optional = true) and @JoinColumn(nullable = true) causes this extra join. You may try,

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=417811&siteId=1