I've been trying to understand the DAO pattern but now I have not been successful . Probably because I have not been able to apply what I've found on the internet to problem I try solve. I want to encapsulate the database, do the things right.
I did this so far, but i feel it's pretty useless.
My DTO class:
public class PersonDTO{
final public static String TABLE = "PEOPLE";
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My "DAO"
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public class PersonDAO {
private Connection connection;
private DTO dto;
private Statement stmt = null;
private String tableName;
private Integer id;
public PersonDAO() {
}
public PersonDTO getPerson(int id) {
connection = ConnectionFactory.getInstance();
PersonDTO person = new PersonDTO();
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM " + PersonDTO.TABLE +" WHERE ID = '"+id+"'");
person.setId(rs.getInt("id"));
person.setName(rs.getString("age"));
} catch (SQLException e) {
e.printStackTrace();
}
closeConnection();
return person;
}
public void save() {
throw new UnsupportedOperationException(); //not implemented yet
}
public void update() {
throw new UnsupportedOperationException(); //not implemented yet
}
public void delete() {
throw new UnsupportedOperationException(); //not implemented yet
}
public List<DTO> getDTO(String filter) {
return null;
}
protected void closeConnection() {
try {
connection.close();
connection = null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
I can't get:
- Which it is supposed to be the relationship between the DTO class and the DAO class.
- The DAO class has to have the methods for get the information from the database?
- What is DTO class for, why just don't use a "Person" class instead?.
This is pretty frustrating. I will be grateful with any help.