Spring JPA如何通过locationId和categoryId查询Events实体,Repository需做哪些修改
解决方案
你需要按照Spring Data JPA的派生查询规则修改Repository接口,具体修改如下:
方案1:使用Spring Data JPA自动派生查询(无需手动写SQL)
利用JPA的属性导航规则,关联实体的嵌套属性可以用_分隔指定,修改后的EventsRepository代码如下:
@Repository public interface EventsRepository extends JpaRepository<Events,Long> { // 注意:如果同一个分类+地点可能匹配多个事件,返回值建议改为 List<Events> List<Events> findByCategories_CategoryIdAndLocation_LocationId(Long categoryId, Long locationId); // 如果你确定最多只会有一个匹配结果,可以保留单个返回值 // Events findByCategories_CategoryIdAndLocation_LocationId(Long categoryId, Long locationId); }
规则说明:
Categories是你关联的分类实体字段名,_CategoryId表示取关联的Categories实体的categoryId属性Location是你关联的地点实体字段名,_LocationId表示取关联的Location实体的locationId属性- 方法入参顺序要和方法名里的属性顺序对应,也可以用@Param显式绑定参数避免顺序错误
方案2:使用@Query自定义查询(更灵活,适合复杂逻辑)
如果后续有扩展逻辑的需求,可以手动写JPQL查询:
@Repository public interface EventsRepository extends JpaRepository<Events,Long> { @Query("SELECT e FROM Events e WHERE e.categories.categoryId = :categoryId AND e.location.locationId = :locationId") List<Events> listEventsByCategoryAndLocation(@Param("categoryId") Long categoryId, @Param("locationId") Long locationId); }
调用方式
Controller层拿到locationId和categoryId后直接调用对应方法即可:
// Controller层调用示例 List<Events> events = eventsRepository.findByCategories_CategoryIdAndLocation_LocationId(categoryId, locationId);
注意事项
- 你原有代码里的方法名
findByCateoryAndLocation存在两处错误:一是分类字段名拼写错误(实体里字段是categories不是Cateory),二是没有指定关联实体的查询属性 - 如果单个分类+地点下可能存在多个事件,不要用单个Events作为返回值,否则会抛出
NonUniqueResultException异常
内容的提问来源于stack exchange,提问作者jammy
相关产品推荐
相关产品推荐

