Spring JPA Repository按外键查询报错:找不到Post的'id'属性
问题原因分析
Spring Data JPA的方法命名规则会自动解析查询条件:当你定义findByPostId这类方法时,框架会先尝试在Comment实体中寻找名为postId的字段,找不到的话会将PostId拆分为Post和Id,随后去关联的Post实体中查找id属性。如果你的Post实体主键字段不是id(比如是postId),就会抛出No property 'id' found for type 'Post'的错误;同理YeditepeUserDetails相关查询报错也是同样原因。
解决方案
有两种可行的解决方式:
方式一:修正Repository方法命名
按照关联实体的实际主键字段名调整方法命名,遵循findBy关联对象_主键字段名的格式:
假设Post实体的主键字段是postId,YeditepeUserDetails的主键字段是yeditepeUserDetailsId,修改后的Repository代码如下:
@Repository public interface CommentRepository extends JpaRepository<Comment, Long> { List<Comment> findByYeditepeUserDetails_YeditepeUserDetailsIdAndPost_PostId(Long yeditepeUserDetailsId, Long postId); List<Comment> findByYeditepeUserDetails_YeditepeUserDetailsId(Long yeditepeUserDetailsId); List<Comment> findByPost_PostId(Long postId); Comment findByCommentId(Long commentId); }
如果YeditepeUserDetails的主键字段是id,则对应方法改为findByYeditepeUserDetails_Id即可。
方式二:使用@Query注解自定义查询
如果不想修改方法名,可以通过@Query编写JPQL语句来实现查询,明确指定关联实体的主键字段:
@Repository public interface CommentRepository extends JpaRepository<Comment, Long> { @Query("SELECT c FROM Comment c WHERE c.yeditepeUserDetails.yeditepeUserDetailsId = :userId AND c.post.postId = :postId") List<Comment> findByYeditepeUserDetailsIdAndPostId(@Param("userId") Long yeditepeUserDetailsId, @Param("postId") Long postId); @Query("SELECT c FROM Comment c WHERE c.yeditepeUserDetails.yeditepeUserDetailsId = :userId") List<Comment> findByYeditepeUserDetailsId(@Param("userId") Long yeditepeUserDetailsId); @Query("SELECT c FROM Comment c WHERE c.post.postId = :postId") List<Comment> findByPostId(@Param("postId") Long postId); Comment findByCommentId(Long commentId); }
注意替换JPQL中对应的主键字段名,确保和Post、YeditepeUserDetails实体的实际字段一致。
内容的提问来源于stack exchange,提问作者Adem Galitekin
相关产品推荐
相关产品推荐

