OneToMany:获取集合的大小 [英] OneToMany: get size of collection

查看:116
本文介绍了OneToMany:获取集合的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Data JPA(内部处于休眠状态).我有两个实体Quiz和Question.它们之间的一对多关系.测验有问题清单.如何获得有关测验和问题列表大小的信息?如果我这样写:

I'm working with Spring Data JPA(Hibernate inside). I have two entities Quiz and Question. OneToMany relation between them. Quiz has list of Question. How can I get information about Quiz and size of list of Question? If I write like that:

Quiz quiz = quizRepository.findOne(1);
int questionCount = quiz.getQuestions().size();

Hibernate生成两个查询:

Hibernate generates two queries:

  1. 选择有关测验的信息
  2. 选择所有问题

但是我只需要测验信息和问题的大小.

But I need only Quiz information and size of Questions.

不选择第二项怎么办?

How can I do it without second select?

推荐答案

目前尚不清楚您是要避免第二个SQL查询还是要完全避免将问题加载到内存中.

It is not clear from your question whether you want to merely avoid the second SQL query or whether you want to completely avoid loading the questions into memory.

如其他地方所述,您可以通过在关系本身上或通过加载测验的条件/JPQLquery指定获取模式来处理第一种情况.这将在一个SQL查询中加载所有内容,但仍然会产生加载问题的开销:加载问题对于您而言可能不是问题,但对于大型数据集,如果您只需要计数,则开销可能会很大.

As noted elsewhere you can deal with the first scenario by specifying the fetch mode either on the relationship itself or via a criteria/JPQLquery which loads the quiz. This will load everything in one SQL query but you will still have the overhead of loading the questions: loading the questions may not be an issue in your case but for large datasets the overhead may be considerable if you only need a count.

对于第二种情况,您有各种选择.特定于Hibernate的非便携式解决方案是利用Hibernate的@Formula批注.

For the second scenario you have various options. Hibernate specific non-portable, solutions would be to make use of Hibernate's @Formula annotation.

如何使用JPA和Hibernate映射计算的属性

class Quiz{
    @Formula("select count(*) from question where quiz_id = id")
    int numberOfQuestions;
}

或使用休眠@LazyCollection(LazyCollectionOption.EXTRA)属性,该属性允许您调用size()而不加载所有记录.

or to use the Hibernate @LazyCollection(LazyCollectionOption.EXTRA) property which allows you to call size() without loading all the records.

这两种方法都会为您提供许多问题,而无需将整个集合加载到内存中.

Both of which which will give you the number of questions without loading the entire collection to memory.

第二种非特定于Hibernate的可移植解决方案是创建一个视图vw_quiz_summary_data,该视图将具有相同的信息.然后,您可以将其映射为普通实体,并以一对一关系或@SecondaryTable的形式将其链接到测验.

The second, non-Hibernate specific, portable, solution is to create a view say vw_quiz_summary_data which would have the same information. You can then map this as normal entity and link it to a Quiz as either a one-to-one relation or as a @SecondaryTable.

这篇关于OneToMany:获取集合的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆