Hibernate有效地检索多个集合

时间:2018-11-03 13:16:52

标签: hibernate

我有一门课叫做发票。 它具有以下收藏。

@OneToMany(mappedBy = "taxInvoiceLinkId.invoice")
private List<TaxInvoiceLink>       taxLinks;

@OneToMany(mappedBy = "invoiceCustomInfoLinkId.invoice")
private Set<InvoiceCustomInfoLink> customInfos = new LinkedHashSet(0);

要有效地获取这两个集合(就往返次数和内存而言),我应该

选项1:加入两者均通过

    Session session = SessionFactoryHandler.getSession();
    List result = null;
    session.beginTransaction();
    Query query = session.createQuery
                  (" From Invoice Inv left join fetch "+
                   " Inv.taxLinks left join fetch Inv.customInfos where 
                   invoice.id = 1");
    result = query.list();
    session.getTransaction().commit();
    return result;

选项2:作为两个语句执行

  Session session = SessionFactoryHandler.getSession();
    List result = null;
    session.beginTransaction();
    Query query = session.createQuery
                  (" From Invoice Inv left join fetch Inv.taxLinks
                       where invoice.id = 1" );
    result = query.list();

    query =  session.createQuery
                  (" From Invoice Inv left join fetch Inv.customInfos where 
                   invoice.id = 1");
    result = query.list();
    session.getTransaction().commit();
    return result;

1 个答案:

答案 0 :(得分:0)

使用Set替换列表,并在映射中添加FetchType EAGER

@Entity
Class Result{
    @OneToMany(mappedBy = "taxInvoiceLinkId.invoice",fetch=fetch=FetchType.EAGER)
    private Set<TaxInvoiceLink>       taxLinks;

    @OneToMany(mappedBy = "invoiceCustomInfoLinkId.invoice",,fetch=fetch=FetchType.EAGER)
    private Set<InvoiceCustomInfoLink> customInfos;
}

然后使用条件检索您的实体

Session session = SessionFactoryHandler.getSession();
List result = null;
session.beginTransaction();
Query query = session.createCriteria(Result.class);
List<Result> result = query.list();