Data Access Object in Java

Data Access Object in Java


Posted in : Java Posted on : April 20, 2012 at 7:19 PM Comments : [ 0 ]

In this tutorial you will learn about the Java Data Access Object design pattern

Data Access Object Design Pattern

The Data Access Object (DAO) is a technique which separates the business logic from application persistence data and a way to access the access the persistence data through API. DAO hides the data access logic of data source from application logic. By using DAO you can use different data access mechanism without effecting the business logic.

An example of DAO is given below,

In the example given below we have used mainly four packages which separates the application logic

  • Database -> This package consists database connection class and DAO class of all the tables. The DAO class contains all the methods that can be performed on a particular table.
  • Domain -> This contains the persistence domain objects of the application.
  • Application -> This is package contains the application business logic.
  • Services -> This package methods to access the data source.

Please consider the following table to go throw the example

CREATE TABLE student (                
           roll_no int(11) NOT NULL,           
           address varchar(255) default NULL,  
           course varchar(255) default NULL,   
           name varchar(255) default NULL,     
           PRIMARY KEY  ('roll_no')              
         );

Domain class of the application

Student.java

package net.roseindia.domain;

public class Student {
	private int rollNo;
	private String name;
	private String course;
	private String address;

	public Student() {

	}

	public Student(int rollNo, String name, String course, String address) {
		this.rollNo = rollNo;
		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;
	}

}

Database Connection class

ConnectionClass.java

package net.roseindia.database;

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

public class ConnectionClass {
	private static String driver;
	private static String userName;
	private static String password;
	private static String connectionUrl;
	private static String database;

	public static Connection getConnection() {
		driver = "com.mysql.jdbc.Driver";
		userName = "root";
		password = "root";
		connectionUrl = "jdbc:mysql://localhost:3306/";
		database = "data";
		Connection connection = null;
		try {
			Class.forName(driver);
			connection = DriverManager.getConnection(connectionUrl + database,
					userName, password);
			return connection;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
}

StudentDaoClass.java

package net.roseindia.database;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import net.roseindia.domain.Student;

public class StudentDaoClass {
	public void addStudent(Student student) {
		try {
			Connection connection = ConnectionClass.getConnection();
			Statement statement = connection.createStatement();
			String sql = "INSERT INTO student(roll_no, address, course, name) VALUES('"
					+ student.getRollNo()
					+ "', '"
					+ student.getName()
					+ "', '"
					+ student.getCourse()
					+ "', '"
					+ student.getAddress()
					+ "')";
			statement.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

Service Class

ApplicationService.java

package net.roseindia.service;

import net.roseindia.database.StudentDaoClass;
import net.roseindia.domain.Student;

public class ApplicationService {
	private StudentDaoClass studentDaoClass = new StudentDaoClass();

	public void addStudent(Student student) {
		studentDaoClass.addStudent(student);
	}
}

Form to add the details

StudentForm.java

package net.roseindia.application;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import net.roseindia.domain.Student;
import net.roseindia.service.ApplicationService;

import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;

class StudentForm extends JFrame implements ActionListener {
	JButton SUBMIT;
	JPanel panel;
	DefaultFormBuilder builder;
	JLabel rollLabel, nameLabel, courseLabel, addressLabel;
	final JTextField rollText, nameText, courseText, addressText;

	StudentForm() {
		rollLabel = new JLabel();
		rollLabel.setText("Roll No:");
		rollText = new JTextField(25);

		nameLabel = new JLabel();
		nameLabel.setText("Name:");
		nameText = new JTextField(25);

		courseLabel = new JLabel();
		courseLabel.setText("Course:");
		courseText = new JTextField(25);

		addressLabel = new JLabel();
		addressLabel.setText("Address:");
		addressText = new JTextField(25);

		SUBMIT = new JButton("SUBMIT");

		builder = new DefaultFormBuilder(new FormLayout(""));
		builder.setBorder(BorderFactory.createEmptyBorder(20, 4, 20, 4));
		builder.appendColumn("center:pref");
		builder.appendColumn("5dlu");
		builder.appendColumn("fill:max(pref; 100px)");

		builder.append("Roll No:", rollText);
		builder.nextLine();
		builder.append("Name:", nameText);
		builder.nextLine();
		builder.append("Course:", courseText);
		builder.nextLine();
		builder.append("Address:", addressText);
		builder.nextLine();
		builder.append(SUBMIT);

		add(builder.getPanel());
		SUBMIT.addActionListener(this);
		setTitle("STUDENT REGISTRATION FORM");
	}

	public void actionPerformed(ActionEvent ae) {
		int rollNo = 0;
		String name = nameText.getText();
		String course = courseText.getText();
		String address = addressText.getText();

		String rollString = rollText.getText();

		if (rollString.length() > 0) {
			rollNo = Integer.parseInt(rollString);
		}
		setVisible(false);

		if (rollNo != 0 || name.length() > 0 || course.length() > 0
				|| address.length() > 0) {

			Student student = new Student();
			student.setRollNo(rollNo);
			student.setName(name);
			student.setCourse(course);
			student.setAddress(address);
			ApplicationService service = new ApplicationService();
			service.addStudent(student);
		} else {
			JOptionPane.showMessageDialog(this,
					"Please Specify All Fields Correctly");
		}
	}
}

MainClazz.java

package net.roseindia.application;

import javax.swing.JOptionPane;

public class MainClazz {
	public static void main(String arg[]) {
		try {
			StudentForm frame = new StudentForm();
			frame.setSize(400, 200);
			frame.setVisible(true);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
		}
	}
}


When you run this application it will display message as shown below:


Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics