如何在不查询实体的情况下对 jpa 的 @ManyToOne JoinColumn 执行 "in" 查询

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

我有一个像这样的实体:

@Entity
class Blog{
    @Id
    private Long id;

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

我想在 author 列上执行 "in" 查询,所以我写了 BlogRepository 这样的:

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

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

这行得通,但是,我需要为一个请求执行两个查询,即从 UserRepository 查询 User 实体以获取 Collection<User> users。 因为在很多情况下,我想要的只是语义:

select * from blog where author_id in (some_id_list);

那么 jpa 中有没有让我在不查询 User 实体的情况下执行如下查询的方法?

您方法的 Order 部分妨碍了您。由于您不想对结果进行排序,因此可以使用:

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

    Page<Blog> findByUser_IdIn(Collection<Long> userId, Pageable pageable);
}

是的,您也可以编写自定义 JPQL

public 接口 BlogRepository 扩展了 JpaRepository,CustomizedBlogRepository {

@Query("select b from Blog b LEFT JOIN b.author.authorId in :authorIds")
Page<Blog> getByUsersByIds(List<Integer> authorIds, Pageable pageable);

}

在这里您可以将 authorId 更改为用户 table 的任何 Id,您有 created.And 您也可以尝试 JOIN 而不是 左连接