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

Spring Boot下JPA+Hibernate查询指定父实体下模糊匹配名称的子元素方法

实现方案

你可以直接通过子实体DefaultGroup的Repository完成关联模糊查询,有两种常用实现方式:


方案1:手写JPQL查询(和你现有写法逻辑对齐)

直接在DefaultGroup对应的Repository接口中添加以下方法,利用子实体自带的compania关联属性做父ID筛选,同时做名称模糊匹配:

public interface DefaultGroupRepository extends JpaRepository<DefaultGroup, Long> {

    @Query("select dg from DefaultGroup dg where dg.compania.id = :companiaId and lower(dg.name) LIKE lower(CONCAT('%', :keyword, '%'))")
    List<DefaultGroup> findMatchedGroups(@Param("companiaId") Long companiaId, @Param("keyword") String keyword);
}

调用时直接传入父ID和要匹配的关键词即可:

// 查询ID为1的Compania下名称含x的子对象
List<DefaultGroup> result = defaultGroupRepository.findMatchedGroups(1L, "x");

方案2:Spring Data JPA派生查询(无需手写@Query)

按照JPA命名规则写方法名,框架会自动生成对应查询语句,效果和手写JPQL完全一致:

public interface DefaultGroupRepository extends JpaRepository<DefaultGroup, Long> {
    // Containing自动拼接% %,IgnoreCase自动处理大小写匹配
    List<DefaultGroup> findByCompania_IdAndNameContainingIgnoreCase(Long companiaId, String keyword);
}

注意事项

你当前Compania实体的@OneToMany注解缺少mappedBy配置,会导致生成不必要的中间关联表,建议补全配置:

@OneToMany(
    cascade = CascadeType.ALL,
    fetch = FetchType.LAZY,
    orphanRemoval = true,
    mappedBy = "compania" // 对应DefaultGroup实体中的compania属性名
)
private List<DefaultGroup> default_group;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:39:00