aspose file tools*
The moose likes JDBC and the fly likes How to write a simple generic DAO class? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "How to write a simple generic DAO class?" Watch "How to write a simple generic DAO class?" New topic
Author

How to write a simple generic DAO class?

Dennis Zandvliet
Ranch Hand

Joined: Jun 19, 2008
Posts: 60
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

Joined: Mar 10, 2008
Posts: 1760
    
    7

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.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Dennis Zandvliet
Ranch Hand

Joined: Jun 19, 2008
Posts: 60
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

Joined: Mar 10, 2008
Posts: 1760
    
    7

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to write a simple generic DAO class?