Menu

transactions_and_queries

Luis M. Villa

Transactions and Queries

(Return to examples index)

Using transactions in MILK is simple. The objective in mind is to maintain the API and also not making the user responsible of transaction closing, rollback or commit (although you'll always be able to do it on your own).

To make a transaction, we use the onTransaction() method on the database. This method takes as parameters an user-friendly description of the transaction, and a TransactionCode<> that contains the code to execute.

Let's see it using an example:

import net.sourceforge.milk.database.Transaction;
import net.sourceforge.milk.database.TransactionCode;
import net.sourceforge.milk.exceptions.UnableToExecuteQueryException;

...

new IssuesDb().onTransaction("Simple transaction",

    // We have to provide a class that implements
    // TransactionCode<IssuesDb> interface.
    new TransactionCode<IssuesDb>() {

            // The compiler forces us to implement this method, that
            // contains transaction logic.
            @Override
            public void run(final IssuesDb db,
                final Transaction transaction)
                throws UnableToExecuteQueryException {

                // All operations done over db will be executed over this 
                // transaction that's why we don't create new instances of IssuesDb
                System.out.println(db.sql().run(queryAllUsers));
                System.out.println(db.sql().run(queryCountUsers));
                db.sql().run(queryInsertUser);
                db.sql().run(queryDeleteUser);
            }
    }
);

IssuesDb.onTransaction() will be responsible to create the connection, set its autocommit parameter, do the commit after the code is executed, the rollback in case an exception inside the code is thrown and, always, close the connection.

Be careful: only the queries executed over the database provided as parameter in the method TransactionCode.run() will be ran using the transaction. If inside the transaction code we do a new IssuesDb() and execute queries over it, they will use another connection or connections.

And that's all! There is nothing more to tell about MILK and database queries. You want more? Then you have to see how to use MILK's ORM feature.


Related

Wiki: Examples
Wiki: examples_toc
Wiki: orm_examples
Wiki: updates_to_database

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.