Sabine
Sabine

Reputation: 333

JDBC Connection inside DAO layer

Good day,
I try to create DAO layer, following mostly this guide.
Take a note, that I don't use any frameworks, just plain JDBC.

Take a look on creating a Connection instance:
Inside each CRUD method we obtain a connection the following way:

Connection connection = daoFactory.getConnection();

So we obtain a new connection each time we call method.
The only question I have is how to implement transactions here?
I see two solutions:

  1. Instead of DaoFactory field, I use Connection field, which I share among the methods. So as to have one Connection per DAO. But then, what layer should be responsible for transaction? Should I create something in between Service - DAO?
  2. I create fields for other DAO instances needed to create transaction. So as if, for example, I would have TransactionDao to implement banktransfer (take money from one user and add to another) and this TransactionDao will have also UserDao, because I should make one create and two update actions.

I want to know the right solution, maybe it's none of above mentioned.
Tell me please also are there any concurrency issues I should be worry about?
Thank you

Upvotes: 3

Views: 866

Answers (1)

MK.
MK.

Reputation: 34587

The simplest solution is to always perform transaction within a single DAO method, grabbing the connection at the start of the method and passing it to the rest of the methods which run SQL that needs to be part of this transaction. I wouldn't advice you to roll your own alternative to this simplistic approach. Spring will allow you to do this with its behind the scenes magic, and I'm sure there are other frameworks for doing it, dozens of them, but if you want to keep it simple, keep it simple. If some of these methods are also standalone kind, I would do something like this:

public void incBalance(int accountId, int val) {
  Connection conn = daoFactory.getConnection();
  incBalance(conn, accountId, val);
}

private void incBalance(Connection conn, int accountId, int val) {
  con.update(...);
}

public void transfer(...) {
  Connection conn = daoFactory.getConnection();
  conn.beginTransaction();
  ...
  incBalance(conn, acc1, val);
  incBalance(conn, acc2, -val);
  ...
  conn.commit();
}

Upvotes: 1

Related Questions