Data Access Object Design Pattern Java

DAO design pattern works with Data transfer object also known as value object.

DTO is a java class with properties, getter and setter methods.

Now let us create a DTO class.

package com;

import java.io.Serializable;

public class User implements Serializable {

private static final long serialVersionUID = 1L;

private int userId;
private String name;
private String designation;
private int age;

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getName() {
return name;
}

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

public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {
this.designation = designation;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

}

If you See, class definition ,the user class has private field declared as private with getter/setter methods.  The class is serializable because we want to pass DTO between different JVM’s using RMI or any other protocol, it should implement Serializable interface.

TO create DAO Class, We Need to implement following steps.

1.An interface which defines methods for various operations related to DTO

2. Concreate classes which implement DAO interface

3. Factory/Abstract Factory class to get a reference to DAO object.

Now implementing Interface.

package com;

public interface UserDAO {

public void insert(User user);

public void update(User user);

public void delete(int userId);

public User[] findAll();

public User findByKey(int userId);

}

and Implementation class

package com;

public class UserDAOImpl implements UserDAO{

@Override
public void insert(User user) {
// TODO Auto-generated method stub

}

@Override
public void update(User user) {
// TODO Auto-generated method stub

}

@Override
public void delete(int userId) {
// TODO Auto-generated method stub

}

@Override
public User[] findAll() {
// TODO Auto-generated method stub
return null;
}

@Override
public User findByKey(int userId) {
// TODO Auto-generated method stub
return null;
}

}