Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jOOQ - difference between fetchAny and fetchOne

Tags:

java

sql

jooq

Is there a (real) difference between fetchAny() and fetchOne()? Both return exact one record. The API documentation is the same, but the implementation (on github) is different.

like image 885
Appelsien Sap Avatar asked May 18 '15 15:05

Appelsien Sap


2 Answers

The intent of the two methods is different:

  • ResultQuery.fetchOne()

    Returns:

    The resulting record or null if the query returns no records.

    Throws:

    TooManyRowsException - if the query returned more than one record

  • ResultQuery.fetchAny()

    Returns:

    The first resulting record or null if the query returns no records.

In essence, when you use fetchOne() the query must return 0 or 1 record. When you use fetchAny() the query may return any number of records, and if any record is returned by the database, the first one fetched from the JDBC result set will be returned.

Notice that fetchOne() will thus try to fetch 2 records from the JDBC driver (to decide whether TooManyRowsException needs to be thrown), while fetchAny() only fetches at most 1 record.

like image 168
Lukas Eder Avatar answered Nov 16 '22 08:11

Lukas Eder


The javadoc explains the difference. fetchAny() returns the first record, whereas fetchOne() expects the query to return zero or one record, and throws an exception if the query returned more than one record.

like image 27
JB Nizet Avatar answered Nov 16 '22 07:11

JB Nizet