A
A
Anton Ivanov2020-02-02 14:04:16
Java
Anton Ivanov, 2020-02-02 14:04:16

How to make a selection in CrudController by JoinColumn without using join?

Hello.

There is a Comment class that has a user field defined like this:

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


there is such a CommentRepository:

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


I get all user comments like this:

commentRepository.findByUserId(user.getId());

everything works correctly, except that the request looks like this:

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 get rid of this superfluous join'a (after all, you can make a selection immediately by user_id from the comments table).
I do not want to use the @Query annotation, it seems to me that there should be a more correct solution.

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Ivanov, 2020-02-02
@Fly3110

Everything was solved by adding optional=false to @ManyToOne

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question