英文:
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("SELECT u from User u where u.email in :emailIds")
List<User> findUsersByEmailIds(@Param("emailIds") List<String> 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<User> findByEmailIn(List<String> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论