使用hibernate我将从样本表ANIMALS
中提取结果列表。 hibernate方法如下所示:
...
List<Animals> animalList= null;
try {
Query query = session.createQuery("SELECT * FROM animals ORDER BY COLOR , HEIGHT , AGRESSIVE; ");
animalList= query.list();
}
...
结果集的示例如下:
NAME COLOR HEIGHT AGRESSIVE
---------------------------------
JIMMY BLACK SHORT NO
RIPPER BLACK SHORT YES
GOOFY BLACK TALL NO
MURPHY BLACK TALL YES
PAUL WHITE SHORT NO
ROB WHITE SHORT YES
BOBBY WHITE TALL NO
JACK WHITE TALL YES
我的实际结果列表至少有100,000条记录,因此解析列表并为每个记录执行list.add(..)
并不是很明智;
我想要做的是将结果集拆分为8个较小的列表,其中包含COLOR
,HEIGHT
和AGGRESSIVE
的每个组合。
之后,列表将作为参数提供给方法,以便执行一系列操作。
我只能使用Java 1.6或更低版本。
我的主要目标是逃避我采取的IndexOutOfBounds
措施以及IF's
的疯狂行为,如下所示:
for (int i = 0; i < animalList.size(); i++) {
previousAnimal = animals.get(i-1);
currentAnimal = animals.get(i);
nextAnimal = animals.get(i+1);
...//extra code
IF ( previousAnimal.getColor() != currentAnimal.getColor() || previousAnimal.getHeight() != currentAnimal.getColor() || previousAnimal.getAgressive() != currentAnimal.getAgressive() )
...//extra code
IF ( currentAnimal.getColor() != nextAnimal.getColor() || currentAnimal.getHeight() != nextAnimal.getColor() || currentAnimal.getAgressive() != nextAnimal.getAgressive() )
...//extra code
答案 0 :(得分:0)
也许您可以使用DENSE_RANK
分析函数来识别具有相似特征的动物:
...
List<Animals> animalList= null;
try {
Query query = session.createQuery("SELECT a.*, DENSE_RANK() OVER (ORDER BY COLOR, HEIGHT, AGRESSIVE) GRP FROM animals a ORDER BY COLOR, HEIGHT, AGRESSIVE; ");
animalList= query.list();
}
...
结果集的示例如下:
NAME COLOR HEIGHT AGRESSIVE GRP
-------------------------------------
JIMMY BLACK SHORT NO 1
RIPPER BLACK SHORT YES 2
GOOFY BLACK TALL NO 3
MURPHY BLACK TALL YES 4
PAUL WHITE SHORT NO 5
ROB WHITE SHORT YES 6
BOBBY WHITE TALL NO 7
JACK WHITE TALL YES 8
Color
,Height
和Aggressive
的每个不同组合会为GRP
列产生不同的值。然后你可以简化你的其他代码:
for (int i = 0; i < animalList.size(); i++) {
previousAnimal = animals.get(i-1);
currentAnimal = animals.get(i);
nextAnimal = animals.get(i+1);
...//extra code
IF ( previousAnimal.getGrp() != currentAnimal.getGrp() )
...//extra code
IF ( currentAnimal.getGrp() != nextAnimal.getGrp() )
...//extra code