JPA和Postgres:查询外键

时间:2018-03-06 21:15:04

标签: postgresql jpa spring-boot

我有两个实体,

Rater,有一对多映射到评级,

@Entity 
@Table(name = "Rater")
public class Rater {
    @Id
    private Long id;

    @OneToMany(mappedBy = "rater")
    private Set<Rating> ratings;

    /** constructor, getters, setters, etc. */
}

和评级,使用Rater ID的外键

@Entity
@Table(name = "Rating")
    public class Rating {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(referencedColumnName = "id", nullable = false)
    private Rater rater;
}

我想找到评分为3的rater所做的所有评分。我会在Postgres中用以下查询完成此操作:

SELECT rating FROM Rating rating, Rater rater WHERE rating.rater_id = rater.id AND rater.id = 3;

当我将其翻译成我的JPA REST API时

@RepositoryRestResource(collectionResourceRel = "rating", path = "ratings")
public interface RatingRepository extends PagingAndSortingRepository<Rating, Long> {

    @Query("SELECT rating FROM Rating rating WHERE rating.rater.id = :id")
    List<Rating> findByRaterId(@Param("id") Long id);
}

拨打电话时出错

ERROR: column rating0_.id does not exist

如何正确查询外键?

1 个答案:

答案 0 :(得分:1)

更改此行

@JoinColumn(referencedColumnName = "id", nullable = false)

@JoinColumn(name = "rater_id", nullable = false)