This article explains how to perform JDBC operation using a Model object and a Singleton connection class from a MySQL database.
JDBC is an Application Programming Interface for Java which connects a Java application with a database to perform CRUD operations.
Pre requisite:
- JDK 7+ (Click here to download)
- MySQL Database (Click here to download)
- MySQL J Connector (Click here to download)
- JDBC basic (Click here to learn JDBC)
- Eclipse or any other IDE
Model Class: The model class is highly used in the MVC pattern where it works as an intermediate medium between business logic and the view. Usually, a model contains some variables and methods of a specific entity.
Singleton Class: Singleton class is a software design pattern that ensures there will be one single instance of that class. There are multiple ways to achieve a singleton class.
Approach: We are going to create an Organization database that contains an Employee table. We will also create a java application that will connect with the Organization database. The connection will be established by a singleton class which will contain all the necessary driver information. From the java application, we will perform some data manipulation tasks like insert, delete, update and retrieve using a model object of Employee.
- Creating a MySQL database and a table:
create database org; use org; create table employee( emp_id int auto_increment, emp_name varchar(400), emp_address varchar(400), primary key (emp_id) ); - Project setup in eclipse:
- Create a project in eclipse named ‘jdbc’
- Create a folder on that project named ‘jars’ and paste MySQL J Connector on that folder
- Add jars to java build path
- Create 4 package: com.jdbc.util, com.jdbc.dao, com.jdbc.model and com.jdbc.main
- Database connection: Create a singleton connection class DatabaseConnection in com.jdbc.util package. Use your MySQL username and password on the variable user and pass. Look carefully at the last part of the “url” variable. It is mandatory to keep the name the same as the database name. The name of my database is “org” that’s why I put “org” in the URL variable.
DatabaseConnection Class
packagecom.jdbc.util;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;publicclassDatabaseConnection {privatestaticConnection con =null;static{String user ="root";String pass ="root";try{Class.forName("com.mysql.jdbc.Driver");con = DriverManager.getConnection(url, user, pass);}catch(ClassNotFoundException | SQLException e) {e.printStackTrace();}}publicstaticConnection getConnection(){returncon;}}chevron_rightfilter_none - Model class: Create a model class named Employee in com.jdbc.model package. It should contain all the attributes as variables.
Model Class
packagecom.jdbc.model;publicclassEmployee {intemp_id;String emp_name;String emp_address;publicEmployee() {}publicEmployee(String emp_name, String emp_address){this.emp_name = emp_name;this.emp_address = emp_address;}publicintgetEmp_id(){returnemp_id;}publicvoidsetEmp_id(intemp_id){this.emp_id = emp_id;}publicString getEmp_name(){returnemp_name;}publicvoidsetEmp_name(String emp_name){this.emp_name = emp_name;}publicString getEmp_address(){returnemp_address;}publicvoidsetEmp_address(String emp_address){this.emp_address = emp_address;}@OverridepublicString toString(){return"Employee [emp_id="+ emp_id + ",emp_name=" + emp_name + ",emp_address=" + emp_address + "]";}}chevron_rightfilter_none - Database Access Object(DAO): We will create an EmployeeDao interface and another class EmployeeDaoImplementation which implements EmployeeDao. This implemented class will be used as a DAO to perform CRUD operations. We will use PreparedStatement to execute the query. PreparedStatement has 3 special methods:
- executeQuery(): used to retrive data
- executeUpdate(): used to insert, update, delete
- execute(): used to create
EmployeeDao Interface
packagecom.jdbc.dao;importjava.sql.SQLException;importjava.util.List;importcom.jdbc.model.Employee;publicinterfaceEmployeeDao {publicintadd(Employee emp)throwsSQLException;publicvoiddelete(intid)throwsSQLException;publicEmployee getEmployee(intid)throwsSQLException;publicList<Employee> getEmployees()throwsSQLException;publicvoidupdate(Employee emp)throwsSQLException;}chevron_rightfilter_noneEmployeeDaoImplementation Class
packagecom.jdbc.dao;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.List;importcom.jdbc.model.Employee;importcom.jdbc.util.DatabaseConnection;publicclassEmployeeDaoImplementationimplementsEmployeeDao {staticConnection con= DatabaseConnection.getConnection();@Overridepublicintadd(Employee emp)throwsSQLException{String query="insert into employee(emp_name, "+"emp_address) VALUES (?, ?)";PreparedStatement ps= con.prepareStatement(query);ps.setString(1, emp.getEmp_name());ps.setString(2, emp.getEmp_address());intn = ps.executeUpdate();returnn;}@Overridepublicvoiddelete(intid)throwsSQLException{String query="delete from employee where emp_id =?";PreparedStatement ps= con.prepareStatement(query);ps.setInt(1, id);ps.executeUpdate();}@OverridepublicEmployee getEmployee(intid)throwsSQLException{String query="select * from employee where emp_id= ?";PreparedStatement ps= con.prepareStatement(query);ps.setInt(1, id);Employee emp =newEmployee();ResultSet rs = ps.executeQuery();booleancheck =false;while(rs.next()) {check =true;emp.setEmp_id(rs.getInt("emp_id"));emp.setEmp_name(rs.getString("emp_name"));emp.setEmp_address(rs.getString("emp_address"));}if(check ==true) {returnemp;}elsereturnnull;}@OverridepublicList<Employee> getEmployees()throwsSQLException{String query ="select * from employee";PreparedStatement ps= con.prepareStatement(query);ResultSet rs = ps.executeQuery();List<Employee> ls =newArrayList();while(rs.next()) {Employee emp =newEmployee();emp.setEmp_id(rs.getInt("emp_id"));emp.setEmp_name(rs.getString("emp_name"));emp.setEmp_address(rs.getString("emp_address"));ls.add(emp);}returnls;}@Overridepublicvoidupdate(Employee emp)throwsSQLException{String query="update employee set emp_name=?, "+" emp_address= ? where emp_id = ?";PreparedStatement ps= con.prepareStatement(query);ps.setString(1, emp.getEmp_name());ps.setString(2, emp.getEmp_address());ps.setInt(3, emp.getEmp_id());ps.executeUpdate();}}chevron_rightfilter_none - Test the application: Finally, its time to perform the CRUD application using all the methods of EmployeeDaoImplementation. Create a class Application in com.jdbc.main package.
Driver code
packagecom.jdbc.main;importjava.sql.SQLException;importjava.util.List;importcom.jdbc.dao.EmployeeDaoImplementation;importcom.jdbc.model.Employee;publicclassApplication {publicstaticvoidmain(String[] args)throwsSQLException{Employee emp =newEmployee();emp.setEmp_name("Haider");emp.setEmp_address("Mars");EmployeeDaoImplementation empDao=newEmployeeDaoImplementation();// addempDao.add(emp);// readEmployee e = empDao.getEmployee(1);System.out.println(e.getEmp_id() +" "+ e.getEmp_name() +" "+ e.getEmp_address());// read AllList<Employee> ls = empDao.getEmployees();for(Employee allEmp : ls) {System.out.println(allEmp);}// updateEmployee tempEmployee = empDao.getEmployee(1);tempEmployee.setEmp_address("Asgard");empDao.update(tempEmployee);// deleteempDao.delete(1);}}chevron_rightfilter_none
Output:
- For the insert operation, you have to look to your Employee table in the Org database.
- For read one item, use id to fetch data and print it to console.
- For displaying all the items, just call the method and print it to console.
- The update operation should change the updated value into the database.
- The delete operation will delete the information of that id from the database.



