Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @Transaction in JDBI / Dropwizard application

I hava two jdbi dao like these:

public interface dao1 {
  @Query("insert into table1 ...")
  findByid(myBean1);
}

public interface dao2 {
  @Query("insert into table2 ...)
  save(myBean2;
  }
}

i want to execute save of two dao in one transaction like:

dao1.save();
dao2.save();

With spring i have used @transactional annotation. What can i do with dropwizard and jdbi ?

like image 792
LucaA Avatar asked Nov 30 '15 14:11

LucaA


2 Answers

The SQL Object API Overview shows the possibility to bind two instances to the same handle. This way you can both save() calls as part of the same transaction:

// TODO: add try/catch/finally to close things properly
DBI dbi = new DBI("jdbc:h2:mem:test");
Handle h = dbi.open();
h.begin();
Dao1 dao1 = h.attach(Dao1.class);
Dao2 dao2 = h.attach(Dao2.class);
dao1.save(myBean1);
dao2.save(myBean2);
h.commit();
h.close();

If you use onDemand instead of open and hesitate to get try/catch right, you might want to consider something like this:

// add some more interfaces
public interface Dao1 extends GetHandle, Transactional<Dao1> {
   @Query("insert into table1 ...")
   save(myBean1);
}

DBI dbi = new DBI("jdbc:h2:mem:test");
Dao1 dao1 = dbi.onDemand(Dao1.class);

// no try/catch necessary here
dao1.inTransaction(transactional, status) -> {
    transactional.save(myBean1);
    transactional.withHandle((h) -> h.attach(Dao2.class)
       .save(myBean2));
    return null; // return is enforced by the interface
});

Please double-check the functionality with a unit test.

like image 159
ahus1 Avatar answered Sep 17 '22 19:09

ahus1


You can use @Transaction in JDBI. I have blogged about it here. http://manikandan-k.github.io/2015/05/10/Transactions_in_jdbi.html

like image 21
Manikandan Avatar answered Sep 20 '22 19:09

Manikandan