Home Tutorial Java Jdbc Data Access object (DAO) Design Pattern

 
 

Share on Google+Share on Google+
Data Access object (DAO) Design Pattern
Posted on: October 26, 2010 at 12:00 AM
Advertisement
In this tutorial you will learn Data Access Object (DAO) design pattern, and also learn use it in you application

Data Access Object Pattern

Data Access Layer has proven good in separate business logic layer and persistent layer. The DAO design pattern completely  hides the data access implementation from its clients. The interfaces given to client does not changes when the underlying data source mechanism changes. this is the capability which allows the DAO to adopt different access scheme without affecting to business logic or its clients. generally it acts as a adapter between its components and database. The DAO design pattern consists of some factory classes, DAO interfaces and some DAO classes to implement those interfaces.

 

The Data Access object is the primary object of this design pattern. This object abstract the data access implementations for the other object to enable transparently access to the database.
An example given below which illustrates the Data Access Design Pattern.

At first create table named student in MySql database and inset values into it as.

At first create table named student in MySql database and inset values into it as.

CREATE TABLE student (
RollNo int(9)  PRIMARY KEY NOT NULL,
Name tinytext NOT NULL,
Course varchar(25) NOT NULL,
Address text
 );

ConnectionFactory.java

package roseindia.net;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {
	String driverClassName = "com.mysql.jdbc.Driver";
	String connectionUrl = "jdbc:mysql://localhost:3306/student";
	String dbUser = "root";
	String dbPwd = "root";

	private static ConnectionFactory connectionFactory = null;

	private ConnectionFactory() {
		try {
			Class.forName(driverClassName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public Connection getConnection() throws SQLException {
		Connection conn = null;
		conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
		return conn;
	}

	public static ConnectionFactory getInstance() {
		if (connectionFactory == null) {
			connectionFactory = new ConnectionFactory();
		}
		return connectionFactory;
	}
}

StudentBean.java

package roseindia.net;

import java.io.Serializable;

public class StudentBean implements Serializable {
	int rollNo;
	String name;
	String course;
	String address;

	public StudentBean() {

	}

	public StudentBean(int roll, String name, String course, String address) {
		this.rollNo = roll;
		this.name = name;
		this.course = course;
		this.address = address;
	}

	public int getRollNo() {
		return rollNo;
	}

	public void setRollNo(int rollNo) {
		this.rollNo = rollNo;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCourse() {
		return course;
	}

	public void setCourse(String course) {
		this.course = course;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}

StudentJDBCDAO.java

package roseindia.net;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentJDBCDAO {
	Connection connection = null;
	PreparedStatement ptmt = null;
	ResultSet resultSet = null;

	public StudentJDBCDAO() {

	}

	private Connection getConnection() throws SQLException {
		Connection conn;
		conn = ConnectionFactory.getInstance().getConnection();
		return conn;
	}

	public void add(StudentBean studentBean) {
		try {
			String queryString = "INSERT INTO student(RollNo, Name, Course, Address) VALUES(?,?,?,?)";
			connection = getConnection();
			ptmt = connection.prepareStatement(queryString);
			ptmt.setInt(1, studentBean.getRollNo());
			ptmt.setString(2, studentBean.getName());
			ptmt.setString(3, studentBean.getCourse());
			ptmt.setString(4, studentBean.getAddress());
			ptmt.executeUpdate();
			System.out.println("Data Added Successfully");
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ptmt != null)
					ptmt.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	public void update(StudentBean studentBean) {

		try {
			String queryString = "UPDATE student SET Name=? WHERE RollNo=?";
			connection = getConnection();
			ptmt = connection.prepareStatement(queryString);
			ptmt.setString(1, studentBean.getName());
			ptmt.setInt(2, studentBean.getRollNo());
			ptmt.executeUpdate();
			System.out.println("Table Updated Successfully");
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ptmt != null)
					ptmt.close();
				if (connection != null)
					connection.close();
			}

			catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();

			}
		}
	}

	public void delete(int rollNo) {

		try {
			String queryString = "DELETE FROM student WHERE RollNo=?";
			connection = getConnection();
			ptmt = connection.prepareStatement(queryString);
			ptmt.setInt(1, rollNo);
			ptmt.executeUpdate();
			System.out.println("Data deleted Successfully");
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ptmt != null)
					ptmt.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	public void findAll() {
		try {
			String queryString = "SELECT * FROM student";
			connection = getConnection();
			ptmt = connection.prepareStatement(queryString);
			resultSet = ptmt.executeQuery();
			while (resultSet.next()) {
				System.out.println("Roll No " + resultSet.getInt("RollNo")
						+ ", Name " + resultSet.getString("Name") + ", Course "
						+ resultSet.getString("Course") + ", Address "
						+ resultSet.getString("Address"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (ptmt != null)
					ptmt.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
}

MainClaz.java

package roseindia.net;

public class MainClaz {
	public static void main(String[] args) {
		StudentJDBCDAO student = new StudentJDBCDAO();
		StudentBean alok = new StudentBean();
		alok.setName("Alok");
		alok.setRollNo(8);
		alok.setCourse("MBA");
		alok.setAddress("Ranchi");
		StudentBean tinkoo = new StudentBean();
		tinkoo.setName("Arvind");
		tinkoo.setRollNo(6);
		// Adding Data
		student.add(alok);
		// Deleting Data
		student.delete(7);
		// Updating Data
		student.update(tinkoo);
		// Displaying Data
		student.findAll();
	}
}
When you run this application it will display message as shown below:

Data Added Successfully
Data deleted Successfully
Table Updated Successfully
Roll No 1, Name Java, Course MCA, Address Motihari
Roll No 2, Name Ravi, Course BCA, Address Patna
Roll No 3, Name Mansukh, Course M.Sc, Address Katihar
Roll No 4, Name Raman, Course B.Tech, Address Betiah
Roll No 5, Name Kanhaiya, Course M.Tech, Address Delhi
Roll No 6, Name Arvind, Course MBA, Address Alligarh
Roll No 8, Name Alok, Course MBA, Address Ranchi

Download this example code

Advertisement

Related Tags for Data Access object (DAO) Design Pattern:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 26, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com