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

Spring JPA如何查询多对多关联表中指定分类对应的全部用户ID

实现方案

以下是3种常用的实现方式,可根据项目实际场景选择:


方法1:在UserRepository中新增JPQL查询(最常用)

直接通过JPQL关联分类过滤,仅返回用户ID,不需要加载全量实体,性能优异:

import org.springframework.data.jpa.repository.Query;
import java.util.List;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long>{
    Optional<User> findByUsername(String username);

    // 新增查询方法:根据分类ID查询关联的所有用户ID
    @Query("select u.userId from User u join u.categories c where c.categoryId = :categoryId")
    List<Long> findAllUserIdsByCategoryId(Long categoryId);
}

业务层直接调用该方法即可拿到结果。


方法2:通过CategoriesRepository查询

如果项目中已经创建了Categories的Repository,也可以通过关联属性直接获取:

  1. 先定义CategoriesRepository
@Repository
public interface CategoriesRepository extends JpaRepository<Categories, Long> {
}
  1. 业务层逻辑示例
@Service
public class CategoryService {
    @Autowired
    private CategoriesRepository categoriesRepository;

    public List<Long> getUserIdsByCategoryId(Long categoryId) {
        Categories category = categoriesRepository.findById(categoryId)
                .orElseThrow(() -> new RuntimeException("指定分类不存在"));
        // 直接从关联属性中提取用户ID
        return category.getUsers().stream()
                .map(User::getUserId)
                .toList();
    }
}

方法3:原生SQL直接查询中间表(性能最高)

不需要关联实体表,直接操作中间表users_categories,适合数据量较大的场景:

import org.springframework.data.jpa.repository.Query;
import java.util.List;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long>{
    Optional<User> findByUsername(String username);

    // 原生SQL直接查中间表
    @Query(value = "select user_id from users_categories where category_id = :categoryId", nativeQuery = true)
    List<Long> findAllUserIdsByCategoryIdNative(Long categoryId);
}

注意事项

  • 方法2依赖Categories实体中users属性的加载策略,如果你把fetch改为LAZY,需要在业务方法上添加@Transactional注解避免懒加载异常
  • 如果仅需要用户ID不需要完整用户实体,优先选方法1或方法3,避免加载不必要的字段浪费性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:36:04