我正在尝试使用 DESC 获取按日期排序的数据,但我总是使用 ASC 获取数据,
我尝试了两种方法,但没有好的结果:
我有这个存储库:
@Repository
public interface CollectRepository extends JpaRepository<Collect, Long>
第一种方式,我在@query 中使用了排序:
@Query("SELECT c FROM Collect c LEFT JOIN c.payee p WHERE p.userId=:userId AND c.date BETWEEN :startDate AND :endDate ORDER BY c.date DESC")
List<Collect> getCollectionHistory(@Param("userId") String userId,
@Param("startDate") Date startDate,
@Param("endDate") Date endDate);
第二种方式,我使用了排序
@Query("SELECT c FROM Collect c LEFT JOIN c.payee p WHERE p.userId=:userId AND c.date BETWEEN :startDate AND :endDate")
List<Collect> getCollectionHistory(@Param("userId") String userId,
@Param("startDate") Date startDate,
@Param("endDate") Date endDate, Sort sort);
并使用以下方法调用函数:
collectionList = collectRepository.getCollectionHistoryByCollector(userId, startDate, endDate, new Sort(Direction.DESC, "date"));
收集实体
@Entity
@Table(name = "collect")
@SequenceGenerator(name = "SEQ", sequenceName = "collect_id_seq", allocationSize = 1)
@AttributeOverride(name = "id", column = @Column(name = "collect_id", nullable = false))
public class Collect extends GenericEntity {
@Column(name = "collector_user_id")
private String collectorUserId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "payer")
private Payer payer;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "payee")
private Payee payee;
@Column(name = "amount", precision = 5)
private BigDecimal amount;
@Column(name = "date", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
@JsonSerialize(using = IsoDateSerializer.class)
private Date date;
@Column(name = "reason")
private String reason;
@Column(name = "reference")
private String reference;
// getters and setters
收款人实体:
@Entity
@Table(name = "payee")
@SequenceGenerator(name = "SEQ", sequenceName = "payee_id_seq", allocationSize = 1)
@AttributeOverride(name = "id", column = @Column(name = "payee_id", nullable = false))
public class Payee extends GenericEntity {
private String userId;
@OneToMany(mappedBy = "payee", cascade = CascadeType.ALL)
private List<Collect> collects;
@OneToMany(mappedBy = "payee", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<PayeePayer> payeePayers;
我使用的是 Spring Data JPA 版本:1.10.5.RELEASE
这是一个错误还是我的代码有问题?
我该如何解决这个问题?
最佳答案
以下方法将返回 Collect
的列表与 date
之间start
和 end
和 payee
与 ID payeeId
.一旦添加 Payee
对于我可以适应模型的问题。
List<Collect> findAllByPayeeUserIdAndDateBetweenOrderByDateDesc(String payeeUserId, Date start, Date end);
关于java - 按日期字段排序在 Spring Data JPA 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45347618/