在获取父实体时过滤子实体

时间:2018-05-02 11:02:20

标签: java spring hibernate jpa

在获取父实体时,我想要第一个孩子而不是整个孩子列表。 根据子实体的更新日期。

我的父实体:

@Entity
@Table(name = "financial_aid_request_table")
public class FinancialAidRequestEntity extends BaseAuditingEntity {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "id")
    private Integer id;


    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,mappedBy= "financialAidRequest")
    private List<FARWorkFlowHistoryEntity> farWorkFlowHistory;

}

我的孩子实体:

    @Entity
    @Table(name = "far_workflow_history_table")
    public class FARWorkFlowHistoryEntity extends BaseAuditingEntity {

        private static final long serialVersionUID = 1L;
        @Id
        @Column(name = "far_workflow_history_id")
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        private Integer farWorkflowHistoryId;

        @ManyToOne
        @JoinColumn(name = "financialAidRequestId")
        private FinancialAidRequestEntity financialAidRequest;
        @Column(name = "updated_date")
        @NotNull(message = "Update date is mandatory")
        private Timestamp updatedDate;

    }

存储库:

public interface FinancialAidRequestRepository extends JpaRepository<FinancialAidRequestEntity, Integer> {


    List<FinancialAidRequestEntity> findTopByOrderByFarWorkFlowHistoryUpdatedDateDesc(Integer schoolId);
}

执行此操作时,我收到以下运行时错误:

java.util.NoSuchElementException

我在JPA和pgsql数据库中使用spring boot。 有没有办法以这种方式进行过滤? 真的很感激你的帮助。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我已通过在父实体中执行代码来解决此问题。

@Entity
@Table(name = "financial_aid_request_table")
public class FinancialAidRequestEntity extends BaseAuditingEntity {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "id")
    private Integer id;


    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,mappedBy= "financialAidRequest")
    private List<FARWorkFlowHistoryEntity> farWorkFlowHistory;
@ManyToOne(fetch = FetchType.LAZY)
    @JoinFormula("(" +
        "SELECT h.far_workflow_history_id " +
        "FROM tten_farservice_far_workflow_history_table h " +
        "WHERE h.financial_aid_request_id = id " +
        "ORDER BY h.updated_date DESC " +
        "LIMIT 1" +
    ")")
    private FARWorkFlowHistoryEntity latestHistory;

}

希望这个答案能够帮助他人。