You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Data非实体列查询:能否用方法名查询person_id非空的Email

Answer

Great question! You don't need to write a custom @Query for this requirement—Spring Data JPA's query derivation mechanism can handle this perfectly, as long as your entity mapping aligns with the database structure.

Let's break this down based on how your Email entity is mapped:

Case 1: Email entity has a direct personId field

If you've added a personId field to your Email entity (matching the database column), your repository method will work exactly as you wrote it:

public interface EmailRepository extends JpaRepository<Email, Integer> {
    // This works! Spring Data will generate the correct query
    List<Email> findByEmailAddressAndPersonIdNotNull(String emailAddress);
}

Spring Data will automatically generate a query equivalent to:

SELECT e FROM Email e WHERE e.emailAddress = ?1 AND e.personId IS NOT NULL

Case 2: Email entity only has a Person association

If your Email entity uses a @ManyToOne association to Person instead of a direct personId field (like this):

@Entity
public class Email {
    @Id
    private int id;
    private String emailAddress;
    
    @ManyToOne
    @JoinColumn(name = "person_id")
    private Person person;
    // getters/setters
}

You can adjust the method name to check for a non-null Person association (which translates to a non-null person_id in the database):

public interface EmailRepository extends JpaRepository<Email, Integer> {
    List<Email> findByEmailAddressAndPersonIsNotNull(String emailAddress);
}

This will generate the same underlying SQL logic, checking that the person_id column isn't null while matching the email address.

In both scenarios, Spring Data takes care of translating the method name into a valid JPQL query, so no custom @Query is required.

内容的提问来源于stack exchange,提问作者Anton Kolosok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:33:17