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

如何在JPA Repository方法中使用复合主键的部分字段?

解决方案:Spring Data JPA 嵌入式ID属性查询方法

没问题,针对你这种带嵌入式ID的实体类,Spring Data JPA提供了两种简单的方式来实现仅通过secAccount字段查询的方法,我给你详细说下:

方法一:使用Spring Data JPA方法命名规则

因为secAccount是嵌套在AccountLinkKey这个嵌入式ID里的属性,所以你只需要在Repository方法名里通过驼峰嵌套关联实体中的嵌入式ID字段和它内部的属性即可。具体代码如下:

import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface AccountLinkRepository extends JpaRepository<AccountLink, AccountLinkKey> {
    // 方法名规则:findBy[嵌入式ID字段名][内部属性名]
    // 注意内部属性名首字母要大写,对应实体里的secAccount
    List<AccountLink> findByAccountLinkKeySecAccount(String secAccount);
}

这里的accountLinkKey是你AccountLink实体里定义的嵌入式ID字段名,后面紧跟首字母大写的SecAccount,Spring Data JPA会自动解析到AccountLinkKey里的secAccount属性,完成查询。

方法二:使用@Query注解自定义JPQL

如果你觉得方法名太长不够直观,也可以用@Query注解来写自定义的JPQL查询,代码如下:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;

public interface AccountLinkRepository extends JpaRepository<AccountLink, AccountLinkKey> {
    @Query("SELECT al FROM AccountLink al WHERE al.accountLinkKey.secAccount = :secAccount")
    List<AccountLink> findBySecAccount(@Param("secAccount") String secAccount);
}

这种方式更灵活,尤其是当查询条件复杂的时候,可读性会更好。

两种方式都能满足你的需求,返回List<AccountLink>类型的结果,你可以根据自己的习惯选择~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:25:03