首页 > 解决方案 > Spring数据JPA中按时间戳排序

问题描述

我正在尝试从Products我在findByIdOrderByTransactionDateDesc()Spring Boot 应用程序中使用 Spring Data JPA 的表中获取数据。由于我的交易日期是时间戳类型,我无法获得最新时间戳的获取记录的正确顺序。

findByIdOrderByProductsDetails_DateDesc();

我的产品类是:

@Entity
public class Products {
    @Id
    private Integer id;
    private float price;  
    @JsonIgnore
    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL)
    private List<ProductDetails> productsDetails;}

ProductDetails类是:

@Entity
public class ProductDetails implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "transaction_date")
    private Timestamp transactionDate;
    @ManyToOne
    @JoinColumn(name = "product_id")
    @JsonBackReference
    private Products product;
}

标签: spring-bootspring-data-jpatimestampsql-order-by

解决方案


productsDetails 是 OneToMany 关系,您无法使用 Spring Data 存储库方法进行导航。

您必须使用查询:

@Query("select p from Products join productsDetails d where p.id = :id order by d.transactionDate desc")
findByIdOrderByProductsDetails_DateDesc(Integer id);

推荐阅读