我在编写HQL查询以从我的caseid实体中仅选择titlecaseStatusCases字段时遇到困难。返回的案例必须根据caseid有所不同。我不希望包含nameuserid字段。我也不想对caseidtitlecaseStatus字段使用惰性抓取。请注意,caseStatus字段是一对多列表。以下是实体。为了节省空间,省略了吸气剂/吸气剂。

@Entity
@Table(name = "Cases")
public class Cases {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "caseid", nullable = false)
    private Integer caseid;
    private Integer userid;
    private String name;
    private String title;
    @OrderBy("caseStatusId DESC")
    @OneToMany(mappedBy = "cases", fetch = FetchType.EAGER)
    private List<CaseStatus> caseStatus;
}

@Entity
@Table(name = "CaseStatus")
public class CaseStatus {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "caseStatusId", nullable = false)
    private Integer caseStatusId;
    private String info;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "caseid")
    private Cases cases;
}


我的目标是检索仅包含List<Cases>List<Object[]>caseid的Cases实体的不同titleList<CaseStatus>List<CaseStatus>将包含CaseStatus对象,并填充其所有字段。

public List<Object[]> getCases(String title) {
    TypedQuery<Object[]> q = em.createQuery("select distinct c.caseid, c.title, cs "
        + "FROM Cases c join c.caseStatus cs "
        + "where c.title like :title", Object[].class);
    q.setParameter("title", "%" + title + "%");
    List<Object[]> results = q.getResultList();
    return results;
}


上面的方法很接近,但是不正确,因为它没有返回一个索引中的List<CaseStatus>,而是仅返回了一个CaseStatus实体。

例如,如果我的数据库包含单个Case,而List<CaseStatus>的大小为n,则结果将类似于以下示例:

我现在得到的结果示例。不正确:

        List<Object[]> index 0:
            Contains an Object[] where:
                Object[0] = {some caseid}
                Object[1] = {some title}
                Object[2] = {1st CaseStatus}
        List<Object[]> index 1:
            Contains an Object[] where:
                Object[0] = {same caseid as the one found in index 0 above}
                Object[1] = {same title as the one found in index 0 above}
                Object[2] = {2nd CaseStatus}
        ...
        List<Object[]> index n-1:
            Contains an Object[] where:
                Object[0] = {same caseid as all the previous}
                Object[1] = {same title as all the previous}
                Object[2] = {nth CaseStatus}


我希望达到的结果示例:

        List<Object[]> index 0:
            Contains an Object[] where:
                Object[0] = {unique caseid}
                Object[1] = {some title}
                Object[2] = List<CaseStatus> with size of n


更新了问题。我要检索的字段不是nametitleList<CaseStatus>,而是caseidtitleList<CaseStatus>caseid是Cases的主键。

我发现了各种线程Select Collections with HQL - hibernate forumSelect collections with HQL - stackoverflow。这几乎是我遇到的问题。似乎没人在这些线程中找到解决方案。

最佳答案

休眠使查询有些混乱;在HQL中加入这样的成员(不好意思,由于计算机运行不便,我无法在发布前进行测试,但您应该知道这个想法)

select distinct c from Cases c left join fetch c.caseStatus cs where....


“获取”使它渴望。请注意,这将返回Cases类型的数组。您的where子句看起来正确。

09-11 19:27