使用 Spring Data JPA 从 1 table 按列查找并从另一个 table 按列排序

Use Spring Data JPA to Find By Column from 1 table and order by column from another table

我正在尝试使用 ReportedWorkout 中的 WorkoutCaseId 从 2 个不同的表中 return 数据,并使用 Payment 中的 PaymentDate 对它们进行排序。

ReportedWorkout

+-------------------+----------------+
| ReportedWorkoutId | WorkoutCaseId  |
+-------------------+----------------+

付款

+-----------+--------------------+--------------+---------------+
| PaymentId | ReportedWorkoutId  | PaymentDate  | PaymentAmount |
+-----------+--------------------+--------------+---------------+

我想return数据为:

SELECT * FROM ReportedWorkout
JOIN table2 ON ReportedWorkout.ReportedWorkoutId = Payment.ReportedWorkoutId
WHERE WorkoutCaseId = '123'
ORDER BY PaymentDate DESC

@Entity
@Table(name = "ReportedWorkout")
public class ReportedWorkoutEntity extends BaseEntity{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ReportedWorkoutId")
    private Long reportedWorkoutId;

    @Column(name = "WorkoutCaseId")
    private String workoutCaseId;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "ReportedWorkout")
    private Set<PaymentEntity> payments = new LinkedHashSet<>();

...
}
@Entity
@Table(name = "Payment")
public class PaymentEntity extends BaseEntity{

    @Id
    @Column(name = "PaymentId" , nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long paymentId;

    @ManyToOne
    @JoinColumn(name = "ReportedWorkoutId")
    private ReportedWorkoutEntity reportedWorkout;

    @Column(name = "PaymentAmount")
    private BigDecimal paymentAmount;

    @Column(name = "PaymentDate" , nullable = false)
    private LocalDate paymentDate;
...
}

我通过 WorkoutCaseId:

获得了 return 数据
@Repository
public interface ReportedWorkoutRepository extends CrudRepository<ReportedWorkoutEntity, Long> {    
    ReportedWorkoutEntity findByWorkoutCaseId(String workoutCaseId);
}

但我不知道如何按PaymentDate订购?

findByWorkoutCaseIdOrderByPaymentDateDesc 

我收到以下错误:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property paymentDate found for type ReportedWorkoutEntity!

由于 paymentDate 不是 ReportedWorkoutEntity 的 属性,所以错误是有道理的。对于存储库方法,使用相对于 ReportedWorkoutEntity 的 paymentDate 的完全限定名称。

因此:findByWorkoutCaseIdOrderByPaymentsPaymentDateDesc

当你想使用另一个实体时,你必须在你在@Repository 接口中定义的方法签名中提及它。

如@churd 所述,您必须仅使用该格式创建方法签名。

还有另一个选项,如在方法顶部提到的@Query,并在其中定义要执行的sql。