JPA:根据给定列的值列表检索实体列表

huangapple go评论70阅读模式
英文:

JPA: Fetching list of entities by list of values for a given column

问题

我对JPA和Hibernate不太熟悉。

在一个使用案例中,我需要从数据库中获取所有在给定电子邮件列表中具有关联电子邮件的用户。

为了实现这一点,我编写了一个自定义的JPA查询,如下所示:

@Query("SELECT u from User u where u.email in :emailIds")
List<User> findUsersByEmailIds(@Param("emailIds") List<String> emailIdList);

但是,我想知道是否有更好的方法来实现相同的功能?

英文:

I am new to JPA and Hibernate.

In one use case, I need to fetch all users from DB with associated email present in given email list.

To do this, I have written a custom JPA query as follows:

    @Query(&quot;SELECT u from User u where u.email in :emailIds&quot;)
    List&lt;User&gt; findUsersByEmailIds(@Param(&quot;emailIds&quot;) List&lt;String&gt; emailIdList);

But, I would like to know, is there any better way to do the same?

答案1

得分: 1

根据Vishnu的评论,以下是解释:

假设在您的User实体中有一个字段如下:

private String email;

然后在您的repository中可以这样写:

List<User> findByEmailIn(List<String> emailIdList);

这里需要注意的重要关键是findByEmailIn中的Capital E,而在您的实体中此字段为email(小写e)。这样您就可以完全省略@Query语句。

英文:

As commented by Vishnu, here is the explanation:

Assuming in your User entity you have a field like this:

private String email;

Then in your repository you can go like this:

List&lt;User&gt; findByEmailIn(List&lt;String&gt; emailIdList);

The important key thing to notice here is the Capital E in findByEmailIn while in your entity this field was email (small e). This way you can eliminate the @Query statement completely.

huangapple
  • 本文由 发表于 2020年9月1日 09:38:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63680184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定