Spring Data JPA查询报错:Validation failed for query,如何通过movieID查参演演员?
解决方案
一、修复JPQL查询方案
你的JPQL查询报错核心原因是实体名称引用错误,同时优化参数绑定方式可避免潜在问题:
- 你的
RoleEntity标注了@Entity(name = "roles"),JPQL中必须使用roles作为实体名称,而非类名RoleEntity; - 替换位置参数为命名参数,避免参数顺序导致的逻辑错误。
修改后的代码:
@Repository public interface RoleRepository extends JpaRepository<RoleEntity, Long> { @Query(value = "select distinct r.actor from roles r " + "where r.movie.movieID = :movieID") List<ActorEntity> findByMovieID(@Param("movieID") Long movieID); }
二、更简洁的派生查询方案
Spring Data JPA支持通过方法名自动生成查询逻辑,无需手动编写JPQL,更适配你的场景:
@Repository public interface RoleRepository extends JpaRepository<RoleEntity, Long> { // 方法名遵循Spring Data规则:findDistinct[关联属性]By[关联对象].[目标属性] List<ActorEntity> findDistinctActorByMovie_MovieID(Long movieID); }
三、原生查询修复方案
原生查询默认返回Object[]数组,无法直接映射到ActorEntity,可通过结果集映射解决:
- 在
ActorEntity上添加结果集映射配置:
@Entity @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Table(name="actor") @SqlResultSetMapping( name = "ActorMapping", classes = @ConstructorResult( targetClass = ActorEntity.class, columns = { @ColumnResult(name = "id", type = Long.class), @ColumnResult(name = "first_name", type = String.class), @ColumnResult(name = "last_name", type = String.class), @ColumnResult(name = "gender", type = Gender.class) } ) ) public class ActorEntity { // 原有实体代码不变 }
- 修改查询语句指定结果集映射:
@Query(value = "select a.id, a.first_name, a.last_name, a.gender " + "from actor a " + "join roles r on r.actor_id = a.id " + "where r.movie_id = ?1", nativeQuery = true, resultSetMapping = "ActorMapping") List<ActorEntity> findByMovieID(Long movieID);
推荐方案
优先选择派生查询或修复后的JPQL查询,这两种方式符合Spring Data JPA设计理念,代码简洁且不易出错。
内容的提问来源于stack exchange,提问作者Kone
相关产品推荐
相关产品推荐

