【问题标题】:JPA and Postgres: Querying a foreign keyJPA 和 Postgres:查询外键
【发布时间】:2018-08-14 20:32:50
【问题描述】:

我有两个实体,

评分者,与评分有一对多映射,

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

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

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

和评级,具有评级者 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;
}

我想查找 ID 为 3 的评估者所做的所有评分。我会在 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

如何正确查询外键?

【问题讨论】:

    标签: postgresql jpa spring-boot


    【解决方案1】:

    改变这一行

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

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

    【讨论】:

      猜你喜欢
      • 2015-07-15
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 2016-04-20
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多