• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to write a simple generic DAO class?

 
Dennis Zandvliet
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to write a simple generic DAO class to use a single datasource, thus without fancy things like Hybernate, JTA etc.

With the same class i want to retrieve/store single objects but also objects with a parent/child relationship.

My question is what is best practice if you want to hide all the data access logic from the business logic including transactions.

for example if you want to store an Order Header you could write something like this

DAO.storeOrderHeader(){

starttransaction
storeOrderHeader
commit

}

DAO.storeOrderLine(){

starttransaction
storeOrderLine
commit

}

client:
DAO.storeOrderHeader()
DAO.storeOrderLine()


The problem with this code is that storing a complete order should be one transaction:

client:
starttransaction
DAO.storeOrderHeader()
DAO.storeOrderLine()
commit

But now you haven't hide all the implementation details of the DAO layer.

So how do you solve this?
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, you haven't exposed any implementation details, because transaction demarcation shouldn't be the responsibility of the DAO.
DAO's are meant to participate in transactions, not initiate of commit them.
 
Dennis Zandvliet
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jelle Klap wrote:Actually, you haven't exposed any implementation details, because transaction demarcation shouldn't be the responsibility of the DAO.
DAO's are meant to participate in transactions, not initiate of commit them.


But in the case of JDBC to demarcate the transaction you need the connection object and isn't that part of the implementation?
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the JDBC-based DAO ultimately needs a Connection - as a dependecy.
However, the logic and responsibility of obtaining a Connection shouldn't be part of the DAO implementation - think dependecy injection.
If you decouple the Connection and DAO in this manner, transaction demarcation outside of the DAO becomes a possibility.
You could take a look a Spring's (JDBC) DAOSupport and Template classes to get an impression of how this al ties together.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic