Monday 9 June 2014

Create a CRUD application using with DAO design pattern.


DAO or Data Access Object design pattern is good example of abstraction and encapsulation object oriented principles.
It separates persistence logic is a separate layer called Data access layer which enable application to react safely on change in Persistence mechanism.
In short Data Access Object or DAO design pattern is way to reduce coupling between Business logic and Persistence logic

DAO pattern allows you to encapsulate code for performing CRUD operation against persistence from rest of application.
Which means any change on persistence logic will not affect other layers of application which is already tested.

Here i am showing you how to make a CRUD application using with DAO design pattern.




create a table in Mysql database

CREATE TABLE student (
RollNo INT(10)  PRIMARY KEY NOT NULL,
NAME  VARCHAR(50) NOT NULL,
Course VARCHAR(25) NOT NULL,
Address VARCHAR(255)
);


----------------- ConnectionFactory.java -------------------


package com.ramsis.dao;

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/test";
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 com.ramsis.dao;

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 com.ramsis.dao;

import java.io.IOException;
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() throws IOException{

}

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 querySelectId = "SELECT RollNo FROM student where RollNo=?";
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();
}

}
}
}


----------------------------- Main.java ------------------------------
package com.ramsis.dao;

import java.io.IOException;
import java.util.Scanner;

public class Main {
public static void main(String[] args) throws IOException{
Scanner scan  = new Scanner(System.in);
StudentJDBCDAO jdbc = new StudentJDBCDAO();
StudentBean bean = new StudentBean();

String ch="";
String num="";
String name="";
String course="";
String address="";
Integer rollNo;


do{        
System.out.println("please number what you want to do ? ");
System.out.println("1) Add data. ");
System.out.println("2) Update data. ");
System.out.println("3) delete data. ");
System.out.println("4) Show data. ");

num = scan.next();

if(num.equals("1")){

System.out.println("Enter the name : ");
name = scan.next();
bean.setName(name);

System.out.println("Enter Roll Number : ");
rollNo = scan.nextInt();
bean.setRollNo(rollNo);

System.out.println("Enter Course : ");
course = scan.next();
bean.setCourse(course);

System.out.println("Enter the Address : ");
address = scan.next();
bean.setAddress(address);
jdbc.add(bean);
}

else if(num.equals("2")){

System.out.println("Enter the name : ");
name = scan.next();
bean.setName(name);

System.out.println("Enter the roll Number : ");
rollNo = scan.nextInt();
bean.setRollNo(rollNo);
jdbc.update(bean);

}

else if(num.equals("3")){

System.out.println("Enter the roll Number for delete : ");
rollNo = scan.nextInt();
bean.setRollNo(rollNo);
jdbc.delete(rollNo);
}
else if(num.equals("4")){

jdbc.findAll();

}
else
{
System.out.println("Please enter 1 , 2 , 3 , 4 only.");
}


ch = scan.next();
}while(ch.equals("y") || ch.equals("Y"));
System.out.println("Successfully Exit.");
System.exit(0);


}
}



No comments:

Post a Comment