Reputation: 333
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:
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
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