I'm looking for a tutorial / best practice example on how to implement DAO layer in pure Java/JDBC.
Are most DAOs based on Data Mapper pattern ?
Is Active Record pattern also used ?
How do You do it ?
I'm looking for a tutorial / best practice example on how to implement DAO layer in pure Java/JDBC.
Are most DAOs based on Data Mapper pattern ?
Is Active Record pattern also used ?
How do You do it ?
The only thing you need for a DAO is an interface and an implementation. Your interface defines the operations, and the implementation provides the implementation.
The thing that makes a DAO special is that the purpose of the interface and implementation is specifically data access. The way your application handles data access is hidden behind the abstraction of your DAO.
Lets say you see some jdbc code online. You want to use that code in a dao.
Statement st = conn.createStatement();
st.executeUpdate("INSERT INTO sometable " +
"VALUES (...)");
So create an interface
interface ThingDao {
public void save(Thing thing);
}
and your implementation
public ThingDaoImpl implements ThingDao {
ThingDaoImpl() {
// do setup around connections
}
public void save(Thing thing) {
// put the jdbc code here
}
}
Now lets say you want to make your life easy and use something like Spring's JdbcTemplate. The DAO pattern doesn't change. The only change is that in your implementation, you would use the template to perform the operations. That's important because it means that any code that used your Dao doesn't have to change since you did not change the interface. That is the point of the DAO abstraction.
If you want painless JDBC here is my favorite solution...Spring JDBC Template documentation
You will still need to learn about Spring though
There are good books, e.g.:
See the answer for How do I implement a DAO manager using JDBC and connection pools?