Search code examples
javadropwizardjdbijdbi3

JDBI 3 in DropWizard, onDemand reusing connection


Trying to figure out this case from the documentation:

http://jdbi.org/#_attached_to_handle

Say you have

SomeClass dao1 = dbi.onDemand(SomeClass.class)

then you have something in another method, other place:

    try ( Handle handle = dbi.open(); ) {
        SomeClass dao2 = handle.attach(SomeClass.class);

        // What happens here if I use dao1 ? 

        dao1.insert(...)
        dao2.insert(...)
        dao2.insert(...)
        dao1.insert(...)
    }

Note that they are the same type in these cases.

Will there be a new connection / transaction for each insert called or will they all be grouped into one transaction?

It is not clear from documentation.

My thinking is that underneath, both will behave the same and dao1 when invoking insert will check to see if there is an ongoing transaction / connection, and for this type and use that.

However documentation says this true for onDemand instances, however, this dao2 was attached, not an onDemand one as dao1.


Solution

  • Will there be a new connection / transaction for each insert called or will they all be grouped into one transaction?

    Calls to dao2 will be grouped in one transaction from explicitly opened handle.

    Calls to dao1 will use separate transaction per each method call (from Jdbi#onDemand javadoc: an extension which opens and closes handles (as needed) for individual method calls).

    If you want to execute methods from different SqlObject's in the scope of transaction, you have several options:

    • Jdbi#inTransaction/Jdbi#useTransaction: works for both onDemand/attach
    • Combination of @Transaction and @CreateSqlObject, as in the docs