Reputation: 51
I am running a count query using Java 1.6 and Hibernate version 3.2.1 that I expect to return a resultList containing [2]. I am instead getting a result list containing [2, 2, 2, 2]. I turned on debugging to see the hibernate queries allowing me to see the same query being run four times.
The ejbql on the Query I'm running getResultList() on:
SELECT COUNT(*)FROM FlightLogItemEntity AS sectorItem WHERE UPPER(sectorItem.sectorId) = :literal0 AND UPPER(sectorItem.logType) = :literal1
{literal0=0001006711, literal1=TL}
After running getResultList() only once, I see in my logs four identical queries being run:
[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_
At first I thought it might have to do with Entity relationships causing multiple queries to run, but after removing all relationships I still see the same duplicate queries being run.
The code generating the query (after setting the entityManager, ejbql, and Literals):
query.setFirstResult(-1);
query.setFlushMode(null);
query.setMaxResults(-1);
List<?> resultList = query.getResultList();
Does anyone know how I might prevent duplicate queries being run (to prevent duplicate results)?
Upvotes: 3
Views: 1242
Reputation: 764
I'm not sure why its doing the query 4 times, but when you use query.setMaxResults(-1);
you're setting it to return however many items it gets. http://docs.jboss.org/hibernate/orm/3.6/javadocs/org/hibernate/Query.html#setMaxResults(int)
Try changing query.setMaxResults(-1);
to query.setMaxResults(1);
This may just be a band-aid but it should allow you get just one result.
Upvotes: 1