DAO (Data Access Object) is basically a pattern for programming, to use this, you must create a class that will create an object that provides an abstract interface to some type of persistence unit (db, file system. xml, etc).Why is it useful? Because it provides some specific data operations without exposing details of the database.
An basic example of DAO:
import java.util.List;
public abstract class DAOFactory {
public static final int MYSQL_JDBC = 1;
public static final int MYSQL_JPA = 2;
public static final int MYSQL_HIBERNATE = 3;
public abstract List<UserDTO> listAllUsers();
public static DAOFactory getDAOFactory(int whichFactory) {
switch (whichFactory) {
case MYSQL_JDBC : return new MySqlJDBCDaoFactory();
case MYSQL_JPA: return new MySqlJpaDaoFactory();
case MYSQL_HIBERNATE: return new MySqlHibernateDaoFactory();
default: return null;
}
}
}
Then you have to create an specific factory for each type of persistence you will manage in your application, and that specific factory must implement the methods you use for persistence, for example listAllUsers();
For example, for MySQL JPA:
public class MySqlJpaDaoFactory extends DAOFactory {
@Override
public List<UserDTO> listAllUsers() {
// Here I implement specific functionality to retrieve data using JPA Framework
//EntityManagerFactory emf = ...
//EntityManager em = ...
//List<UserDTO> list = em.get...();
//return list;
return null;
}
}
For MySQL JDBC you have to do other process:
public class MySqlJDBCDaoFactory extends DAOFactory {
@Override
public List<UserDTO> listAllUsers() {
//Connection = DriverManager ...
//PreparedStatement ps = connection.prepareStatement("select * from ...");
//ResultSet = ps.executeQuery()
// and so on...
return null;
}
}
Then you invoke your factory this way:
DAOFactory myfactory = DAOFactory.getDAOFactory(DAOFactory.MYSQL_JDBC);
List<UserDTO> list = myfactory.listAllUsers();
And if you can see no matter if you change your database framework or persistence mode, you don't have to re-invent the wheel, just change a parameter and you will get the implementation for persistence you want, just based in a parameter.
Hope it could help you to understand the pattern, I don't use EJB, and if you're using DAO I don't think it is still necessary to implement EJB's.
Best regards