Hibernate getResultList()为计数查询返回重复项

时间:2013-07-18 17:29:05

标签: java hibernate duplicates

我正在使用Java 1.6和Hibernate版本3.2.1运行计数查询,我期望返回包含[2]的resultList。我得到一个包含[2,2,2,2]的结果列表。我打开调试以查看hibernate查询,这样我就能看到相同的查询被运行四次。

查询上的ejbql我正在运行getResultList():

SELECT COUNT(*)FROM FlightLogItemEntity AS sectorItem  WHERE UPPER(sectorItem.sectorId) = :literal0 AND UPPER(sectorItem.logType) = :literal1

{literal0 = 0001006711,literal1 = TL}

只运行一次getResultList()后,我在日志中看到正在运行四个相同的查询:

[SQL] select count(*) as col_0_0_ from SECTOR_ITEM techlogite0_ where upper(techlogite0_.SECTOR_ID)=? and upper(techlogite0_.LOG_TYPE)=? 
[StringType] binding '0001006711' to parameter: 1 
[StringType] binding 'TL' to parameter: 2 
[LongType] returning '2' as column: col_0_0_ 
[SQL] select count(*) as col_0_0_ from SECTOR_ITEM flightlogi0_ where upper(flightlogi0_.SECTOR_ID)=? and upper(flightlogi0_.LOG_TYPE)=? 
[StringType] binding '0001006711' to parameter: 1 
[StringType] binding 'TL' to parameter: 2 
[LongType] returning '2' as column: col_0_0_ 
[SQL] select count(*) as col_0_0_ from SECTOR_ITEM flightlogi0_ where upper(flightlogi0_.SECTOR_ID)=? and upper(flightlogi0_.LOG_TYPE)=? 
[StringType] binding '0001006711' to parameter: 1 
[StringType] binding 'TL' to parameter: 2 
[LongType] returning '2' as column: col_0_0_ 
[SQL] select count(*) as col_0_0_ from SECTOR_ITEM cabinlogit0_ where upper(cabinlogit0_.SECTOR_ID)=? and upper(cabinlogit0_.LOG_TYPE)=? 
[StringType] binding '0001006711' to parameter: 1 
[StringType] binding 'TL' to parameter: 2 
[LongType] returning '2' as column: col_0_0_ 

起初我认为它可能与实体关系有关,导致多个查询运行,但在删除所有关系后,我仍然看到正在运行相同的重复查询。

生成查询的代码(在设置entityManager,ejbql和Literals之后):

query.setFirstResult(-1);
query.setFlushMode(null);
query.setMaxResults(-1);
List<?> resultList = query.getResultList();

有谁知道如何防止重复查询运行(以防止重复结果)?

1 个答案:

答案 0 :(得分:1)

我不确定为什么它会执行4次查询,但是当你使用query.setMaxResults(-1);时,你会将其设置为返回它获得的许多项目。 http://docs.jboss.org/hibernate/orm/3.6/javadocs/org/hibernate/Query.html#setMaxResults(int)

尝试将query.setMaxResults(-1);更改为query.setMaxResults(1);这可能只是一个创可贴,但它应该只允许您获得一个结果。