Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Friday, April 14, 2017

DAO Design Pattern

The Data Access Object(DAO) is one of the J2EE pattern. The DAO pattern hides the implementation details of data source from it's clients,so introducing loose coupling between your core business logic and your persistence mechanism. The main purpose of this Design pattern is to implement persistence layer of the Java application.Here persistence store means all database software like oracle,MySQL.

Let us discuss now without DAO in real projects:

In MVC architecture projects or other projects if persistence logic is mixed up with other logic of the application especially (Business logic)then persistence logic  will not become flexible to modify. That means the modification done in persistence logic may disturb other logics of the application.So, DAO pattern main purpose is to provide a clean design-oriented mechanism for accessing all types of data from your application.

Solution: 
The solution is working with DAO design patter. The java class that separates persistence logic from other logic of the application to make persistence logic as flexible logic to modify is called as DAO design pattern.

DAO class contains:

  • It contains the logic to establish the connection
  • It contains the logic to release the connection
  • It contains the logic to perform persistence operation like insert,update,delete and select
All the above logics of DAO can be developed by using any persistence technology like JDBC,Hibernate,entity Bean components etc...

All the Business components of project can use either single DAO or they can use separate DAO class for each Business components .It is always recommended to write separate DAO class for each Business component.

Now we will understand DAO design pattern with Employee details example:

Create Employee table in MySQL:

CREATE TABLE Employee ( 
EmpId int(1)  PRIMARY KEY NOT NULL, 
Name varchar2(20) NOT NULL, 
DeptName varchar(25) NOT NULL, 
Address text 

 );

Now we will write a java program to make DBConnection:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnector {
String driverClassName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/Employee";
String dbUser = "root";
String dbPwd = "root";
private static DBConnector DBConnector = null;
private DBConnector() {
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 DBConnector getInstance() {
if (DBConnector == null)
{
DBConnector = new DBConnector();
}
return DBConnector;
}
}

Now we will write code for class EmployeeBean:


import java.io.Serializable;
public class EmployeeBean implements Serializable
{
int EmpId;
String name;
String DeptName;
String address;
public EmployeeBean() 
{
}
public StudentBean(int EID, String name, String DeptName, String address) 
{
this.EmpId = EID;
this.name = name;
this.DeptName = DeptName;
this.address = address;
}
public int getEmpId() 
{
return EmpId;
}
public void setEmpId(int EmpId) 
{
this.EmpId = EmpId;
}
public String getName() 
{
return name;
}
public void setName(String name) 
{
this.name = name;
}
public String getDeptName() 
{
return DeptName;
}
public void setDeptName(String DeptName) 
{
this.DeptName = DeptName;
}
public String getAddress() 
{
return address;
}
public void setAddress(String address) 
{
this.address = address;
}
}

Now we will write EmployeeDAO class:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class EmployeeDAO 
{
Connection connection = null;
PreparedStatement ptmt = null;
ResultSet resultSet = null;
public EmployeeDAO() 
{
}
private Connection getConnection() throws SQLException 
{
Connection conn;
conn = DBConnector.getInstance().getConnection();
return conn;
}
public void add(EmployeeBean EmployeeBean) 
{
try {
String queryString = "INSERT INTO Employee(EmpId, Name, DeptName, Address) VALUES(?,?,?,?)";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setInt(1, EmployeeBean.getEmpId());
ptmt.setString(2, EmployeeBean.getName());
ptmt.setString(3, EmployeeBean.getDeptName());
ptmt.setString(4, EmployeeBean.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(EmployeeBean EmployeeBean) {
try {
String queryString = "UPDATE Employee SET Name=? WHERE EmpId=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, EmployeeBean.getName());
ptmt.setInt(2, EmployeeBean.getEmpId());
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 Empid) {
try {
String queryString = "DELETE FROM Employee WHERE EmpId=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setInt(1, EmpId);
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 Employee";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
resultSet = ptmt.executeQuery();
while (resultSet.next()) {
System.out.println("EmpId " + resultSet.getInt("EmpId")
+ ", Name " + resultSet.getString("Name") + ", DeptName "
+ resultSet.getString("DeptName") + ", 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 class:

public class MainClass {
public static void main(String[] args) {
EmployeeDAO employee = new EmployeeDAO();
EmployeeBean emp = new EmployeeBean();
emp.setName("lucky");
emp.setEmpId(6);
emp.setDeptName("Techinical");
emp.setAddress("hyderabad");
EmployeeBean eb = new EmployeeBean();
eb.setName("mahesh");
eb.setEmpId(5);
// Adding Data
employee.add(emp);
// Deleting Data
employee.delete(4);
// Updating Data
employee.update(eb);
// Displaying Data
employee.findAll();
}
}

ALSO READ:

JDBC INTERVIEW QUESTIONS
SPRING INTERVIEW QUESTIONS
STRUTS INTERVIEW QUESTIONS
TOP 20 HR INTERVIEW QUESTIONS
HIBERNATE INTERVIEW QUESTIONS






Saturday, November 19, 2016

Java Design Pattern Interview Questions

In this Page, we will learn frequently asked Design Patterns Interview Questions, which are most managers expect from their developers to have depth knowledge on important patterns. These Interview questions are asked in various java interview. 

Fallowing are the Java Design Pattern Interview Questions:

1) What is Design Pattern?

Ans:

Design Pattern is a general resolution to a commonly occurring problem with in a specific context when designing an application or system . These are tried and tested way to solve particular design issues by various programmers. 


2) What are the elements in Design Pattern?

Ans: There are 3 main elements in Design Pattern . They are

a) Context
b)Problem
c) Solution

a) Context:

It is a recurring situation in which a problem to be solved is found. 

b) Problem:

The problem describes when to apply the pattern. It might describe a specific design problem such as how represent  algorithms as objects. 

c) Solution:

In this pattern provides abstract description of a design problem and how the arrangements of classes and objects to solve it. It works as a template which can be fulfilled with the code.

Note:  The design pattern contains not only above three elements, The relationship between three and formal language that describe the whole business.

3) Can you name few Design Pattern used in Standard JDK library?

Ans:

In JDK library few of the design patterns were used, they are Decorator design pattern which is used in various Java I/O classes,Singleton Pattern which is used in Runtime,Calendar and various other classes,Factory pattern which is used along with various immutable classes like Boolean  and Observer pattern which is used in Swing and many event listener frameworks.



4) What is MVC Design Pattern?

Ans:

MVC means Model-View-Controller, It is a clear functional separation of roles. That means it separate the application logic from the user interface and control between the user interface and the application logic. 

Model: The model represents data and the rules that govern access to and updates of this data. In java program language usually model is Java Beans. The main responsibility of model is to interact with persistence storage to store,retrieve and manipulate data.

View: The view renders the contents of a model. That means it is responsible for displaying results back to the user.This is usually implemented by using JSP.

Controller:  It translates the user's request and select appropriate view to return. The controller job is done by Servelts

5) What is Singleton Design Pattern ?

Ans:  A Singleton is a class which only allows a single instance of itself to be created,and usually gives simple access to that instance. It focus on sharing of expensive object in whole system. Only one instance of of a particular class is maintained in whole application which is shared by all modules.

For more details: Singleton Design Pattern with examples

6) What is factory Design Pattern? where do you use it?

Ans:  The factory Pattern gives us a way to encapsulate the incantations of concrete types. That means it increased level of encapsulation while creating objects. If you use Factory to create object you can later replace original implementation of Products or classes with more advanced and high performance implementation without any change on client layer. 

7) What Front Controller Pattern? Explain?

Ans:  The Front Controller is a entry point to a website. It provides a centralized entry point that controls and manages the web request handling. It is a presentation controller that allows the resources to change without breaking all the bookmarks to a given resource. For Example, Microsoft often changes the contents in it library. The main purpose of this pattern is to isolates the actual resources from direct access by the user. This controller must delegate the request to the proper resource and view.

8)  What is Observer Design Pattern?

Ans:  This pattern is based on communicating changes in state of object to observers so that they can take there action. For example, A whether system where change in weather must be reflected in views to show to public. Here weather object is Subject while different views are Observers. The other way to understand Observer pattern is publisher-subscriber relationship works. Whenever a new issue is published,it gets delivered to you ,but the publisher continues to work as before, since there are other people also subscribed to that particular Magazine.

9) Give example of Decorator Design Pattern in Java?

Ans: The Decorator Design Pattern is to attach the additional responsibilities to an object dynamically. That means enhances capability of individual object. Java IO uses decorator pattern extensively. For example, Buffered classes like BufferedReader and BufferedWriter which enhances Reader and Writer objects to perform Buffer level reading and writing for improved performance. The main purpose of this pattern is adds the responsibility to the components.

10) What is DAO Pattern?

Ans:  DAO means Data Access Object, it provides a connection between the business logic and the resource usually a database tier. It is a general interface to the resource layer. JDBC or Hibernate most commonly used examples for this. It is an object that encapsulates a set of behaviors for accessing a databases,files and other resources. This way you have only one API to deal with rather than a different one for every type of resource.This pattern proved a uniform API to any persistent data storage.



Sunday, December 13, 2015

Singleton Design Pattern In Java

The Single Pattern is one of the Simplest Design Pattern.It involves only one class which is responsible to instantiate itself,to make sure not more than one instance.In the same time it provides a global point of access to that instance. In this case the same instance can be used everywhere,being impossible to invoke directly the constructor each time.


where we used singleton in Real time:

Sometimes It is important to have only one instance for a class.
For Example, in a System there should be only one Window Manager or only a file system or only a print spool. Usually singletons are used in centralized management or internal or external resources and they provide global point of access to themselves .

NOTES:

  1. only one instance of a class is created
  2. provide a global  point of access to that object.


Implementation:
The implementation involves a static member in Singleton class,
a Private Constructor and a static public  method that returns a reference to that static member.

















Static member: Here static member means it contains the Instance of Singleton class
Private Constructor: This will Prevent anybody else to instantiate the Singleton class
static public method: This provides the global point of access to the singleton object and returns the instance to the client calling class.


Singleton Implementation Example:

class Singleton
{
private static Singleton instance;
private Singleton()
{
...
}

public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();

return instance;
}
...
public void doSomething()
{
...
}
}
You can notice in the above code the getInstance() method ensures that only one instance of the class is created. The constructor should not be accessible from outside of the class to ensure the only one way of instantiating the class would be only through the getInstance method.




Note:

The getInstance method is used also to provide a global point of access to the object and it can be used like as Singleton.getInstance.doSomething(). 

No of ways we can apply Singleton in Real time Applications:

I am Providing some example where we exactly use Singleton in Realtime projects while Developing Software Projects.
1)Logger classes
2) Configuration classes
3)Accessing resources in shared mode
4)Thread-safe Implementation for multi threading use


Simple Example for Singleton in Java:


class Singleton

{

private static Singleton instance = new Singleton();



private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}

public static Singleton getInstance()
{    
return instance;
}

public void doSomething()
{
System.out.println("doSomething(): Singleton does something!");
}
}

See also:



High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...