DAO Example
DAO -> Data Access Object is an ideal way to talk to database in any enterprise application.
DAO are used to hide the database related complexity into a separate layer. It helps to separate business layer with database layer.
When using DAO in enterprise application there are generally four layers.
Client
Service
Business Delegate
Data Access
Client : This layer represents the client side. Client layer can be a desktop application GUI or in web application client layer can be browser.
Service : Service layer is the one which provides the service to client. When ever client needs some information it ask the service layer for it. It depends upon the service layer how it generates that information. The service layer may call various business delegates depending upon the request from client.
Business Delegate : Business delegate is responsible for doing business activity. It may run some algorithm to generate some kind of information or it may talk to DAO to get information from database. All business related work is with business delegate.
Data Access : Data Access is directly responsible for communicating to database. It depends upon the Data Access how it talks to database. It may use JDBC or Hibernate to talk to database.
Here is s simple example of saving a employee record into database using these four layers. ( We will use Webwork and Hibernate)
Client : saveEmployee.html
Service : SaveEmployeeAction.java (webwork action)
Business Delegate : BD.java and BDImpl.java (interface and class)
Data Access : EmployeeDAO.java and EmployeeDAOImpl.java (interface and class)
saveEmployee.html
<html>
<form action=”saveEmployee”>
Employee Name:<input type=”text” name=”employeeName”>
<br>
<input type=”submit” value=”Save”>
</form>
</html>
SaveEmployeeAction.java
Public class SaveEmployeeAction extends ActionSupport{
private String employeeName;
private BD bd;//Setter and getter method
public String execute(){
bd=new BDImpl()
;bd.createEmployee(employeeName);
return SUCCESS;
}
}
BD.java
public interface BD{
void createEmployee(String empName);
}
BDImpl.java
public class BDImpl implements BD{
private EmployeeDAO employeeDAO;
public void createEmployee(String employeeName){
employeeDAO=new EmployeeDAO();
employeeDAO.createEmployee(employeeName);
}
}
EmployeeDAO.java
public class EmployeeDAO{
public void createEmployee(String employeeName);
}
EmployeeDAOImpl.java
public class EmployeeDAOImpl{
publics void createEmployee(String employeeName){
SessionFactory sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
Employee employee=new Employee();
Employee.setEmployeeName(employeeName);
session.save(employee);
Transaction.commit();
session.flush();
session.close();
}
}
