Search code examples
javasqlspringhibernatehibernate-mapping

How to perform the "in" query on jpa's @ManyToOne JoinColumn without querying the entity


I have an entity like:

@Entity
class Blog{
    @Id
    private Long id;

    // ...
    @ManyToOne
    @JoinColumn(name = "author_id")
    private User author;
}

And I want to perform an "in" query on the author column, so I wrote my BlogRepository like:

public interface BlogRepository extends JpaRepository<Blog, Long>, CustomizedBlogRepository {

    Page<Blog> findByUserIn(Collection<User> users, Pageable pageable);
}

This works, however, I need to perform two queries for one request, that is to query the User entity from UserRepository to get Collection<User> users. Because in many situation, all I want is semantic like:

select * from blog where author_id in (some_id_list);

So is there anyway in jpa to let me perform query like below without querying the User entity?


Solution

  • The Order part of your method gets in the way. Since you don't want the results ordered, you can use this:

    public interface BlogRepository extends JpaRepository<Blog, Long>, CustomizedBlogRepository {
    
        Page<Blog> findByUser_IdIn(Collection<Long> userId, Pageable pageable);
    }