简体   繁体   English

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

[英]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:我想对author列执行“in”查询,所以我写了我的BlogRepository如下:

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 .这是有效的,但是,我需要对一个请求执行两次查询,即从UserRepository查询User实体以获取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?那么在 jpa 中有没有让我在不查询User实体的情况下执行如下查询?

The Order part of your method gets in the way.您的方法的Order部分会妨碍您。 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);
}

Yes you can also write custom JPQL是的,您也可以编写自定义 JPQL

public interface BlogRepository extends JpaRepository, CustomizedBlogRepository {公共接口 BlogRepository 扩展 JpaRepository,CustomizedBlogRepository {

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

} }

Here you can change authorId to any Id of User table, which you have created.And you can also try JOIN instead of LEFT JOIN在这里,您可以将 authorId 更改为您创建的 User 表的任何 Id。您也可以尝试JOIN而不是LEFT JOIN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM